1

I am new to react hooks. I am trying to cast API response into an array using react useState hook. It's giving me empty with the below approach

const [post, setPostArray] = useState([]);

useEffect(() => {
  const postparams = { userList: result };
  axios
    .get(environment._urlPosts, { headers, params: postparams })
    .then(posts => {
      // storing response data in array
      setPostArray(posts.data.post);

      console.log(post);
    })
    .catch(err => {});
}, []);

Then I used the below approach and I was able to see data is printing in the console log

axios.get(environment._urlPosts, { headers, params: postparams }).then(posts => {
  // storing response data in array
  for (let obj of posts.data.post) {
      post.push(obj)
  }
  setPostArray(post)
  console.log(post)

But when I try to iterate this post array in my JSX, it's giving me empty array.

  </div>
{/* array length */}
        {post.length}

        {post.map(post =>
            <div className="card">
                <Post username={post.username} fullname={post.fullname} postedTime={post.postedTime} postContent='Hi' tweeterLike={post.tweeterLike} />
            </div>
        )}

Can you please help me to resolve this?

3
  • Since setState work like an async function you will not get the post state right after your set it. but you should be able to get that in the JSX Commented Mar 22, 2020 at 9:51
  • yeah 1st approach worked with JSX. Thanks. Commented Mar 22, 2020 at 11:04
  • 1
    Actually ur 1st comment resolved my problem. But anyway I accepted the provided answer also :) Commented Mar 22, 2020 at 14:55

1 Answer 1

4

Here is a minimal Example of what you are trying to achieve. This is the working code:

import React, {useEffect, useState} from "react";
import "./styles.css";

export default function App() {
  const [post, setPostArray] = useState([])

  useEffect(() => {
    fetch('https://jsonplaceholder.typicode.com/todos/1')
    .then(response => response.json())
    .then(json => {
      console.log(json);
      setPostArray([json]);
  })
    //  setPostArray([{name: 'a'}, {name: 'b'},{name: 'c'}])
},[])

console.log(post)
  return (
    <div className="App">
      {
        post.map(item => <div>{item.title} </div>)
      }
    </div>
  );
}

Here is the link to the example in codeSandBox: https://codesandbox.io/s/jovial-snow-773kp

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.