I have finally got my first Redux store working and I can access my user json no problem however I am unable to to access my fields json that is in the store. The fields data is in the store the same as user data however when I go to use useSelector it returns undefined when I console.log.
The user json is the one in the auth field below and is accessed correctly by state.user however when I enter either state.fields or state.fields.data neither work.
How do I go about accessing this data? I want to have the fields array de-structured so that I can access the list individually.
// select user object from redux
const user = useSelector(state => state.user);
// get the object with all the fields
const fields = useSelector(state => state.fields);
// can destructure individual fields
const { diveSchoolList,
currentList,
regionList,
diveTypeList,
visibilityList,
diveSpotList,
marineTypeList,
articleList } = fields;
I expect that you’ll get an object with a property called fields. If you look at your data, it looks like you have nested properties both called “fields”, like state.fields.fields. I would assume there is an issue in your tree structure or in the way the reducer saves the data.
Yes I have two reducers called user as one if for adding actions and the other is a switch statement auth. The json is labelled user for authentication in the backend which is what is causing it .
I think my problem is because my createAsyncThunk is causing my Redux Tree in store to be created like fields.fields or fields.data and then I also have empty arrays in the first fields branch then the second branch has the populated ones.
This causing me problems when I access the data for fields by using for example use fields.data.fieldList for a dropdown then when I try to re-render the page I get a fields.data is undefined error. Ideally my first branch of redux should be populated and then when re-render I don’t get any errors.
Yeah, you have to make your components that can handle empty data. When I write unit tests, I like to pass in empty data and make sure it doesn’t crash. You can have some kind of fast return null if the data is empty or have a spinner, or maybe if you’re lazy you just leave an empty component on the screen - just make sure it isn’t going to crash.
I haven’t worked with thunk in a long time. I don’t know. But the plain fact is that you have state.fields.fields.data before you get to the actual data and you’re trying to access that with a selector for state.fields. Have you tried
I’m not sure what you mean. I see neither a mapStateToComonents nor a mapStateToProps. I haven’t used useSelector before (but I’ve used similar non-hook things) but I imagine that part of the point is that if you’re using useSelector you don’t need mapStateToProps. Both serve the purpose of hooking into the redux store.