Home > database >  How can I set useState with an array of dataresults from the database?
How can I set useState with an array of dataresults from the database?

Time:10-28

Compiles ok but Getting undefined in state. Appreciate any advice!

customer_data = customer_data?.listCustomers[0];

console.log(customer_data?.sunday_open);  /// returns 08:00:00
const [accountInfo, setAccountInfo] = useState({ "sunday_open_hours": customer_data?.sunday_open.split(":")[0], 
"sunday_open_mins" : customer_data?.sunday_open.split(":")[1]});
console.log(accountInfo)

this code:

console.log(accountInfo)

returns:

{sunday_open_hours: undefined, sunday_open_mins: undefined}

CodePudding user response:

Maybe because it takes time to load the data so in this case you need to wait/watch for a change of the retrieved data and update the state according to it. Like this in short

export default function App() {
  const [accountInfo, setAccountInfo] = useState({}) 
  useEffect(() => {
    if (customer_data)
    setAccountInfo({ "sunday_open_hours": customer_data?.sunday_open.split(":")[0], 
  "sunday_open_mins" : customer_data?.sunday_open.split(":")[1]});
  },[customer_data])
  console.log(accountInfo)
}

CodePudding user response:

The issue is that the value is undefined when you initialize state. Instead you should update state once the value is defined, in a useEffect.

const App = () => {
  const [accountInfo, setAccountInfo] = useState({});
  
  useEffect(() => {
    fetchData()
      .then(data => {
        const [sunday_open_hours, sunday_open_mins, sunday_open_secs] = data.listCustomers[0].sunday_open.split(':');
        setAccountInfo({ sunday_open_hours, sunday_open_mins });
      });
  }, []);
};

CodePudding user response:

Can you provide a working example or how you are using that at your component?

Also, I suppose that this customer_data value is coming from a request. I'm not fully certain but it seems that the console.log() call is dispatched before the value is fully fetched, the useState() call works directly at that moment and after some time when the console.log() starts to execute, the screen get the reference that is already fetched (I'm supposing a lot of things here)

But, you should be able to use something like this and update the state after the fetch:

function MyComponent() {
  const [accountInfo, setAccountInfo] = useState();
  const customer_data = fetchCustomersData();

  useEffect(() => {
    setAccountInfo(customer_data?.sunday_open)
  }, [setAccountInfo, customer_data]);

  const [hours, mins] = accountInfo?.split(":");

  return (
    <p>
      {hours || "00"}:{mins || "00"}
    </p>
  )

Another thing you could think of is: the state can be something simple and other variables can depend on it. If the state change, those variables should also change.

Hope this helps you!

  • Related