ReactFix
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • React
  • React Native
  • Programming
  • Object Oriented Programming

Friday, October 28, 2022

[FIXED] How can I set useState with an array of dataresults from the database?

 October 28, 2022     react-hooks, reactjs, state   

Issue

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}

Solution

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)
}


Answered By - DINO
Answer Checked By - - Timothy Miller (ReactFix Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Google+
  •  Stumble
  •  Digg
Newer Post Older Post Home

Featured Post

Is Learning React Difficult?

React is difficult to learn, no ifs and buts. React isn't inherently difficult to learn. It's a framework that's different from ...

Total Pageviews

Copyright © ReactFix