VersifiXion
VersifiXion

Reputation: 2292

Get Redux state values

EDIT: I think the issue is with my reducers I only have one reducer called "filmsReducer" where I do this at the end :

export default combineReducers({
  films: filmsReducer
});

I'm doing an app in React Native using Redux,

I want to get the initialState values below in a component :

const initialState = {
  name: "",
  likedFilms: [299534, 49530, 629],
  dislikedFilms: [100241, 559969]
};

const filmsReducer = (state = initialState, action) => {
  const { likedFilms, dislikedFilms } = state;
  switch (action.type) {
    case ADD_FILM:
      if (action.array === "like") {
        const newLikedFilms = [...state.likedFilms, action.payload];

        return {
          ...state,
          likedFilms: newLikedFilms
        };
      } else {
        const newDislikedFilms = [...state.dislikedFilms, action.payload];

        return {
          ...state,
          dislikedFilms: newDislikedFilms
        };
      }

    default:
      return state;
  }
};

And here's the component, I want to get likedFilms array from the redux state in the props of this component, but the console log doesn't work :

class LikedScreen extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log(this.props.likedFilms); <-- doesn't work
  }
}

const mapStateToProps = state => ({
  likedFilms: state.likedFilms
});

export default connect(mapStateToProps)(LikedScreen);

Upvotes: 0

Views: 104

Answers (2)

Nouman Janjua
Nouman Janjua

Reputation: 410

It will be like, use reducer name as while mapping props in Component

class LikedScreen extends Component {
  constructor(props) {
    super(props);
  }

  componentDidMount() {
    console.log(this.props.likedFilms); <-- doesn't work
  }
}

const mapStateToProps = state => ({
  likedFilms: state.films.likedFilms
});

export default connect(mapStateToProps)(LikedScreen);

Upvotes: 0

Tim
Tim

Reputation: 10719

Regarding your comment, you probably have to adapt your code to the following:

Edit Regarding another comment of yours, you need to change it to films instead of FilmsReducer:

const mapStateToProps = state => ({
  likedFilms: state.films.likedFilms
});

Upvotes: 4

Related Questions