1

I'm a newbie to React/Redux and I could use your advice on how to structure the following data models in my react app.

I have the following models:

Users
Skills (id, title)
UserSkills (user_id, skill_id)

I want to create a component that shows a User's Skills which I would get from my API /user_skills which would return (user_id, skill_id).

Should I update my API to include the extra fields I need to render the component like Skill.title or should I somehow, with Redux, also store Skills in the Redux store, and the have UserSkills somehow find the Skill.Title from the Redux store and if it doesn't exist, go fetch the title? How can I best structure this in Redux and how can I get started?

halfer
  • 19,824
  • 17
  • 99
  • 186
AnApprentice
  • 108,152
  • 195
  • 629
  • 1,012

2 Answers2

1

The key word is "normalization". Once you have normalized state, you would want to look up the right Skill entry based on a skill_id in your mapStateToProps function.

See Redux Many to Many Relationship , Redux: Normalizing Global State , and React-Redux-Links for prior discussion and links to more information.

Edgar
  • 6,022
  • 8
  • 33
  • 66
markerikson
  • 63,178
  • 10
  • 141
  • 157
  • If I have a list of 50 skills, would that result in 50 queries to the api? – AnApprentice Jun 05 '17 at 16:01
  • 2
    Ah... sorry, I may have misread the question a bit. Thought you were asking about how to store them in Redux, not specifically about API structure. No, typically you might make one API request that returns many different data fields/types, and then insert them all in a normalized structure in your Redux store. – markerikson Jun 05 '17 at 16:18
0

So I will start by answering your first question.

Should I update my API to include the extra fields I need to render the component like Skill.title?

Yes you should. Change your API to such that when you provide a user id, it should return all the skills particular to that user. Your API should like something like api/user_skills/:id

Now you have changed your API lets move to Redux. The way Redux works is that you dispatch a certain action and against each action we have a reducer which updates your store and the concerned components are listening to changes in the store via the connect method provided by the react-redux library.

So I will conclude by highlighting the overall flow. In your React component you will dispatch actions (actions can make AJAX requests), against each action you will write a reducer which will update your app's store. On each successful AJAX request, store will be updated and the component(s) which have subscribed to the store will re-render as the entire store will be available to them via props.

Hope I am able to answer your question :)

Abdul Samad
  • 441
  • 2
  • 11