0

A week into learning React, and I've hit a snag.

So, I have an action/reducer setting up an external API to pass the payload into the state for my component to render some of the values out in a subcomponent (being passed as a prop object) - however, it takes a few seconds for the API to respond and obviously I cant ask react to render any values before then, as they return null and crash react..

Best practise? Set default values for the state values until the state gets updated to avoid the null errors? Is there a better way?

Have tried a conditional render on the subcomponent (which will render the values) but didn't work.

Any advice greatly appreciated!

1
  • "Have tried a conditional render on the subcomponent...but didn't work" Show your code. I'd say this is the best practise: check if state was loaded and render a loading indicator if not. Commented Aug 1, 2017 at 8:14

1 Answer 1

4

You must first set some initial value of state inside of reducers which is generally null or empty object. Now inside of your render method you must use conditional rendering and return appropriate jsx from that. This is the standard way to get data from APIs and then rendering it inside of the component. This could probably help you.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks @Shubham - That was helpful - finally managed how to set an initialState for the array.
How would I go about setting an initial state to map a list against @Shubham Jain? ['org_units', [ ['', ''] ]], ['positions', [ ['', ''] ]], I'm getting some React errors... TypeError: Cannot read property 'map' of undefined
I am not able to understand what you are trying to do. Could you please elaborate?
Thanks for the replies. Let me do some digging, and get back to you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.