0

I am trying to fetch data from the api ,storing it in redux store first and then trying to get it by useSlector and then storing it in local state ..when console.log i am getting the data but i am not able to store in in my local state.It is showing empty . I have included the image of console and my code.Please check

code

console

tanmay
  • 39
  • 1
  • 8
  • Post code here as formatted code, not in images or via links. Also, there are plenty of answers here that deal with async data. https://stackoverflow.com/questions/14220321/how-do-i-return-the-response-from-an-asynchronous-call – crashmstr Jun 10 '20 at 12:45

1 Answers1

0

Try to add

useEffect(() => {
 if (resultData) setLogs(resultData)
}, [resultData])

it will populate your state (logs) whenever resultData changes

Also you can just use your resultData(as well as loadingdata) straight in the component, for example, where you do logs.map(log => ...) just by resultData.map(log => ...) (don't forget to check it's not empty). And you can omit the logs and loading variables.

Sergei Klinov
  • 730
  • 2
  • 12
  • 25
  • Thank you for the solution.It is wokring perfectly.Can u please explain what exactly we did here.I mean i tried to add this in the existing useeffect but it didnt work and started calling api indefinately.but when i tried in seperate useffects it is working perfectly.can u please tell why – tanmay Jun 10 '20 at 16:26
  • @tanmay The `useEffect()` added has the dependency of `resultData`, so it is fired every time when `resultData` changes. And if it's not empty it sets your state. And the existing `useEffect(()=> {},[])` with empty dependency array is working like `componentDidMount()` You can learn more about hooks in the official documentation https://reactjs.org/docs/hooks-reference.html – Sergei Klinov Jun 10 '20 at 16:36