D
D
Daniil2018-06-26 11:07:31
React
Daniil, 2018-06-26 11:07:31

How to pass user data from store to React + React Router?

Good morning. There is such a question. I assumed we have a user repository (I note, without a back and, accordingly, without a database). For example userStorage.js :

const users = [
  {
    id: 1,
    name: 'Every Interaction',
    username: 'EveryInteract',
  },
  {
    id: 2,
    name: 'AppleInsider',
    username: 'appleinsider',
  },
];

And there is App.js, in which we start our work:
...
import users from './userStorage';
...
 <BrowserRouter>
      <React.Fragment>
        <Nav />
        <Switch>
          <Route path="/:user" component={Profile} />
          <Redirect exact from="/" to="/EveryInteract" />
        </Switch>
      </React.Fragment>
    </BrowserRouter>

I do not quite understand how I can properly validate and pass the required user data? (In our case, now only username and name).
That is, a person clicked or typed in the profile name, for example .../EveryInteract, and how do we check and get the necessary data from our storage and pass it to the Profile?
Somehow using a ternary to check the url? { location.href === users.id ? ... } and than
<Route path="/:user" render={() => <Profile prop1 prop2 />} /> ?

Please tell me how is it right

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2018-06-26
@TchernyavskD

(if react-router version 4)
You will have in this.props.match.params.user what the person entered after / for the route: Therefore, in componentDidMount of the Profile component, if you need to "emulate" data loading, through setTiemout or just directly in the render component, you can use this ( ) value and that's it. How you will get the user object from the data array is up to you. You can search in an array, you can make a method in the same file and export it, for example:

export function findUserById(id) => {
  // ищем по id элемент в массиве и возвращаем его
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question