Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to setState with fetched data in React

I need to setState with an object that I’m getting from a redux store. The problem is when I call setState in my component I am getting undefined. Any idea on how to set a default value of state with fetched data?

Here is my component:

import React, { useEffect, Fragment, useState } from 'react';
import { useSelector, useDispatch } from 'react-redux';

const contactDetails = useSelector((state) => state.contactDetails)

const upFields = contactDetails?.contact?.data?.fields


const [contact, setContact] = useState({
    fields:  upFields <---- this is returning undefined.. The name is correct, but maybe setState is running too fast? 
  })
  

console.log(contact) <---- this shows {fields: undefined}



console.log(upFields) <---- this console.logs just fine

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you use useEffect() and trigger it using the object

useEffect(()=>{
  setContact(fetched_data)
}, [fetched_data]) // <-- data array will trigger every time this data change

you can trigger it on first component mount with

useEffect(()=>{
  setContact(fetched_data)
}, []) // <-- empty array will only trigger once
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading