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

2

16

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.

Saki answered 17/1, 2016 at 17:0 Comment(0)
H
18

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

Hayner answered 17/1, 2016 at 17:5 Comment(4)
Thank you very much for this :)Saki
@Dylan, I found out that _find(state, {id: ownProps.params.id}) will work fine. From this _.find(state, 'id', ownProps.params.id) I was not getting proper results.Externality
Since filter was introduced, you can directly use this.state.filter(item => item.id == id);Rompish
@PatrickMutuku filter is gonna return an array there -- you'll also want to grab the first indexed item -- filter(..)[0]. Also nowadays you can use Array.prototype.find if supported.Hayner
C
0

import _ from 'lodash'; const mapStateToProps = (state, ownProps) => ({ item: _.find(state.data, (e) => e.product_id == ownProps.match.params.productID) });

Here product_id is a label present in the API, and productID is the parameter I gave in the react-router.

ATTENTION: do not forget the match keyword

Cultural answered 6/8, 2020 at 7:23 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.