Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Redux - how to get an element from store by id

For the past weeks I've been trying to learn React and Redux. Now I have met a problem thay I haven't found a right answer to.

Suppose I have a page in React that gets props from the link.

const id = this.props.params.id;

Now on this page, I'd like to display an object from STORE with this ID.

 const initialState = [
      {
        title: 'Goal',
        author: 'admin',
        id: 0
      },
      {
        title: 'Goal vol2',
        author: 'admin',
        id: 1
      }
    ]

My question is: should the function to query the the object from the STORE be in the page file, before the render method, or should I use action creators and include the function in reducers. I've noticed that the reduceres seem to contain only actions that have an impoact on store, but mine just queries the store.

Thank you in advance.

like image 299
Kethmar Salumets Avatar asked Jan 17 '16 17:01

Kethmar Salumets


People also ask

How do you get items from Redux store?

It's simple to get access to the store inside a React component – no need to pass the store as a prop or import it, just use the connect function from React Redux, and supply a mapStateToProps function that pulls out the data you need. Then, inside the component, you can pass that data to a function that needs it.

How do you get data from Redux store using useSelector?

If you want to retrieve multiple values from the store, you can: Call useSelector() multiple times, with each call returning a single field value. Use Reselect or a similar library to create a memoized selector that returns multiple values in one object, but only returns a new object when one of the values has changed.

What is store getState ()?

getState()​Returns the current state tree of your application. It is equal to the last value returned by the store's reducer.


1 Answers

You could use the mapStateToProps function to query the store when you connect the component to redux:

import React from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';

const Foo = ({ item }) => <div>{JSON.stringify(item)}</div>;

const mapStateToProps = (state, ownProps) => ({
  item: _.find(state, 'id', ownProps.params.id)
});

export default connect(mapStateToProps)(Foo);

(This example uses lodash - _)

The mapStateToProps function takes in the whole redux state and your component's props, and from that you can decide what to send as props to your component. So given all of our items, look for the one with the id matching our URL.

https://github.com/rackt/react-redux/blob/master/docs/api.md#arguments

like image 131
Dylan Avatar answered Sep 24 '22 19:09

Dylan