Home > front end >  state value is undefine in react js
state value is undefine in react js

Time:09-29

I get the data from the backend and store it into the state (post). when I use post.name then it shows undefined.

const [post, setPost] = useState([]);
   
    const getAllUser = async () => {
      const response = await fetch("http://localhost:4000/getpost");
      response.json().then((res) => setPost(res.data.Post));
      // console.log(post);
    };
    
    
    useEffect(() => {
      getAllUser();
    }, []);
    
    const component = post.component;  // value is undefine
    console.log(component);

CodePudding user response:

In the pass I used the setState callback so now you might like to use:

https://maksimrv.medium.com/usestate-with-callback-d574298eb8bd

because you want to read a state variable's value immediately after it has been updated.

CodePudding user response:

You need to validate if post is populated before accessing post.name.

If you're using babel, you can do it like this:

post?.name

If you're not using babel:

post ? post.name : 'empty'

CodePudding user response:

Try and handle all your async logic in useEffect

useEffect(() => {
  getAllUser();
  
  async function getAllUser () {
    const response = fetch("http://localhost:4000/getpost");
     const json = await response.json()
     setPost(json.data.Post);
  // console.log(post);
};
}, []);

CodePudding user response:

When you're manipulating the state, you should use useEffect(), for instance:

useEffect(() => { 
    // Do something with the updated post object here.
}, [ post ]);
  • Related