Git Product home page Git Product logo

map-state-to-props-lab's Introduction

Mapping State to Props Using React and Redux

Objectives

  • Use the React Redux library to connect the store to the React application.
  • Utilize the <Provider /> component, the connect function and mapStateToProps to access Redux store content.

Overview

In this lesson, we want to explore how mapStateToProps is used to connect regular React components with the Redux store. This is also a good opportunity to review the steps for using the redux and react-redux packages in your app.

Instructions

Some files are provided, including UserInput and the reducer, manageUsers, but the Redux store isn't fully hooked up yet.

Connecting to Redux

In src/index.js, use the createStore method from redux, passing in the provided reducer, manageUsers, to create a store. Use Provider from react-redux to wrap <App />, passing store as a prop to the Provider. This will give your components access to the store.

Test by Dispatching an Action

Run npm start and open up your browser's dev console. If everything is connected correctly in index.js, a form should appear in the browser. Submitting something using the form will cause a console.log to fire in our reducer, indicating that the values have been added to our store.

In UserInput.js, we can see the code that fires when we press the submit button:

...

handleOnSubmit = (event) => {
  event.preventDefault();
  this.props.dispatch({type: 'ADD_USER', user: this.state})
}

render() {
  return(
    <form onSubmit={this.handleOnSubmit}>
      ...
    </form>
  )
}

We can see that, on submit, handleOnSubmit() is called. event.preventDefault() is called to stop the page from refreshing, then this.props.dispatch() is called with a custom action, {type: 'ADD_USER', user: this.state}.

export default connect()(UserInput);

Wrapping a component in connect as we see above will, by default, pass one function to props: dispatch(). This makes it possible for us to dispatch custom actions, as we see here in handleOnSubmit().

We will go into greater detail on how we can customize our dispatches using connect, but using this.props.dispatch() like this is a handy way to allow any component to interact with the store.

Mapping State

Now that we've got a working store, we want to get access to it and display the contents of our store's state.

  1. Connect the Users component similar to how it is connected in UserInput.

  2. Write a function in Users.js, but outside of the Users class, called mapStateToProps. mapStateToProps accepts one argument, state, the current version of your store's state. Use state to access the array of users. Your mapStateToProps function should return an object with keys. Each key will become a prop in your component, allowing you to assign values based on the provided state.

The Users component should display the username of a user submitted to the store. To pass the final test, it should also display a total count of current users. Try to use mapStateToProps to solve both, returning two keys, one for users and one for the userCount.

Conclusion

With all tests passing, you should have a working form that adds and successfully displays usernames, as well as a total count of those users. While these are small bits of data, we've got a fully integrated React/Redux application, ready to be expanded upon!

map-state-to-props-lab's People

Contributors

dependabot[bot] avatar ihollander avatar jeffkatzy avatar lizbur10 avatar lukeghenco avatar maxwellbenton avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

map-state-to-props-lab's Issues

I want to echo sentiments that this is a confusing lab

The readme before this lab tells the readers that using connect and mapStateToProps is a little hard to wrap one's head around and does not give much explanation as to how it works. It is a little frustrating to then be presented with a lab without more explanation as to what is going on. I think that explaining a little more how writing a mapStateToProps function works and what it returns would be very helpful. I understand that a great way to learn is to synthesize a solution from previous information, but it felt as though we weren't given enough information to synthesize from. Also, the comments in the curly braces did more harm than good.

Any reason we're using an ancient version of webpack here?

Webpack has deprecated the docs for version 1.x. Any reason we're using that here in lieu of a newer version like 3 or 4?

We're not able to do this import here:

import ConnectedUsers from './Users'

when we've exported using

export default connect(mapStateToProps)(Users)

I feel like that should have worked, but we needed to use destructuring instead.

Needs a rework

This lab has poor instruction, inconsistent structure and incorrectly named components. There are 6 open issues, none of which appear to be addressed. This is disappointing.

UserInput.js explanation doesn't match up with code given

The 2nd and 3rd paragraphs in the section Test by Dispatching an Action discuss the file UserInput.js.

The text in the ReadMe doesn't match up with what is given in the file UserInput.js itself.

Learning MapStateTopProps and Connect() is difficult to understand at first, but seeing code that doesn't exist be explained is especially weird.

Please fix this section.

Some concepts should be clarified in readme before doing this lab

I do not think mere mortals like myself have enough information beforehand to understand that <ConnectedUsers /> can be called without any apparent props passed, yet have access to this.props.users within the Users class component. Only after looking at the solution does it make sense that props are obtained through whatever is declared in the mapStateToProps method. The readme discusses this, but without a concrete example, the discussion isn't solid.

Also, I'm all for 'getting the band back together', but the reducer file name should be changed from manageBands.js to manageUsers.js.

Bug in test code

The last test can be defeated if you render the users name and hometown with an <h3> and <h4> tag since the test is just looking for a 3 and then a 4 in the HTML somewhere.

An easy fix for the test would be to put more names in state than there are header tags.

this lab doesn't has unnecessarily confusing differences relative to the readme

I can't get a single test to pass even though the store appears to be updating and logging my state updates to the screen.

I don't know if my code is running as is expected for the tests so I looked up the answer and had a few questions based on the code shown.

In App.js

Before starting, why does it say {/* is there something we could connect to here? */} in curly brackets? Based on previous lessons, I knew that we needed to enter a Component here but we were not taught to enter a component in with {brackets around it} so it threw me off as I didn't think a Component wrapped in brackets was syntax that was going to work and it does.

In Users.js
Naming the exported component "ConnectedUsers" was very confusing as the readme shows a default export of the connect method in which we use a MapStateToProps method with and a Component that has the same name as the file. However your answer uses a named export instead and makes things much more confusing.

The whole time in App.js, i'm expecting to export a "Users" Component but the answer shows you export "ConnectedUsers."

I feel like the name change of the Component to a named export const was unnecessary and adds confusion since this was not done in the readme and if I recall, none of the lessons prior.

Here is the code I used which works in the browser but fails all tests. The overall code changes needed to make this lab work are subtle but I feel as though the comments within the labs and the Component name change in Users.js add a lot more confusion to this lab than there needs to be. You never talk about named exports in this course and you always default export in readme's and labs so to randomly spring it here in this lab lesson with no explanation is insane.

`

App.js
import React, { Component } from 'react';
import UserInput from './components/UserInput'
import Users from './components/Users'

export class App extends Component {
render() {
return (





);
}
}

export default App;

Users.js
import React, { Component } from 'react';
import { connect } from 'react-redux';

export class Users extends Component {

render() {
let users = this.props.users.map((user, index) =>

  • {user.userName}
  • );

    return (
      <div>
        <ul>
          {users}
        </ul>
      </div>
    )
    

    }
    }

    const mapStateToProps = (state) => {
    return {
    users: state.users,
    primaryUser: state.users[0]
    };
    };

    export default connect(mapStateToProps)(Users)

    `

    Misleading lesson

    I saw one other person open an issue that there is not enough guidance in this lesson. I agree, and I'd like to elaborate a bit.

    One of the most misleading things (other than it having a totally different file tree than the instructional lab before it) about this lesson is that when you open it up, portions of the code have curly brackets with comments inside them (ex. {/* stuff should happen around here */}). Since curly brackets are a big part of React, this registers as "okay, I should be putting code inside these curly brackets." However, this is not the case! The curly brackets need to be removed altogether, but we have no way of knowing that.

    My suggestion would be removing the comments from the lab itself, and having a more informative Readme (i.e. the other labs in this course), because it makes little sense to have it set up this way.

    New syntax introduced?

    I had trouble figuring out what to do with export const ConnectedUsers = Users. I don't think it was covered in a prior lesson.

    The comments on where to add code are not consistent

    In some places there are comments to add code, however it's not in all of the places necessary to get the tests to pass. There should be comments in all places where additional code is needed or not at all. It's confusing that only some are commented.

    Recommend Projects

    • React photo React

      A declarative, efficient, and flexible JavaScript library for building user interfaces.

    • Vue.js photo Vue.js

      ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

    • Typescript photo Typescript

      TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

    • TensorFlow photo TensorFlow

      An Open Source Machine Learning Framework for Everyone

    • Django photo Django

      The Web framework for perfectionists with deadlines.

    • D3 photo D3

      Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

    Recommend Topics

    • javascript

      JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

    • web

      Some thing interesting about web. New door for the world.

    • server

      A server is a program made to process requests and deliver data to clients.

    • Machine learning

      Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

    • Game

      Some thing interesting about game, make everyone happy.

    Recommend Org

    • Facebook photo Facebook

      We are working to build community through open source technology. NB: members must have two-factor auth.

    • Microsoft photo Microsoft

      Open source projects and samples from Microsoft.

    • Google photo Google

      Google โค๏ธ Open Source for everyone.

    • D3 photo D3

      Data-Driven Documents codes.