Source:  Twitter logo

I'm having a little problem with connect(). I thought wrapping all components in Provider is going to work, but turns out it isn't.... So I found that I need to use connect() from react-redux. The problem is i don't know how should I use it. This site is showing some examples but, i don't have any action creators to put inside connect because I don't use them....... Can someone give me some advices? I just want to access my store inside components...

In order to use your store in your container you need to do two things

Firstly : make use of mapStateToProps() . As the name suggests, it maps the state variables from your store to the props that you specify

Secondly : You need to connect these props to your container. This is where connect() comes into picture. The object returned by the mapStateToProps component is connected to the container. You can import connect from react-redux like import {connect} from 'react-redux';

Example

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

class App extends React.Component {
  render() {
    return <div>{this.props.containerData}</div>;
  }
}

function mapStateToProps(state) {
  return { containerData: state.appData };
}

export default connect(mapStateToProps)(App);
8 users liked answer #0dislike answer #08
Shubham Khatri profile pic
Shubham Khatri

You might have better luck with the Redux documentation here.

Here's a simple example of how the connect function works:

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

class Item extends React.Component {
  render() {
    return <div onClick={() => this.props.dispatch( /* some action here */ )}>{this.props.name}</div>;
  }
}

function mapStateToProps(state) {
  return { name: state.name };
}

export default connect(mapStateToProps)(Item);

What happens above is when you export the Item component, you're exporting the wrapped, connected component. Wrapping the component will pass in the prop name from the app state (it will also pass in the dispatch function as a prop.

2 users liked answer #1dislike answer #12
Ben Nyberg profile pic
Ben Nyberg

Copyright © 2022 QueryThreads

All content on Query Threads is licensed under the Creative Commons Attribution-ShareAlike 3.0 license (CC BY-SA 3.0).