I'm moving a React app from class to functional components where it makes sense to, however I'm having a little trouble with the useContext hook, or perhaps just the context API in general.
My application supports authenticated and non-authenticated states. For authenticated users I would like to make an API call which returns details of items that they own and present this in a table. Because this list is reasonably static I would like to store it in context and pass it down to child components which will show different views on that data. I don't want to be going back to that API for different components. Authenticated users and non authenticated users will also be able to see items that other people own by visiting their pages/routes eg user/one, user/two. I think this data will be stored in the component state.
I have a stackblitz at https://stackblitz.com/edit/react-jvmryf which shows what I am doing.
I have created a context (UserContext) which is shared to child components and ideally I would like the value of UserContext.data to provide the value of the table, but it seems that when the component is rendered the data is not available. This is visible in the console logs where HERE IS USERCONTEXT {"name":"alice","age":30,"data":{}} is printed a few times, before eventually it prints with the data object being populated.
Currently the NewTable component is getting data for the table via an API call in the component so you can see how the table should look.
I would really appreciate advice on if I am making the API call and setting to Context in the correct place, and how I should be rendering that data in child components (in this specific case NewTable, although there will be other components in the future).
Your context is not available because fetchUser runs asynchronously and has not completed when your NewTable renders. I don't know what "if I am making the API call and setting to Context in the same place" means, but the approach you're taking is workable.
If you don't want to render that table before data is loaded, a common approach is to add some mind of "loading" state to your shared context to signal to the child components that data is not ready. You could render some "is loading" or progress bar or something until the data becomes loaded.