Notice: This page requires JavaScript to function properly.
Please enable JavaScript in your browser settings or update your browser.
学ぶ Creating the Profile Slice | Creating a React-Redux Application
/
Introduction to Redux

bookCreating the Profile Slice

メニューを表示するにはスワイプしてください

We will create the Profile slice to store the user data, such as a name from the DetailsSection, so we can access it from the PostsSection and display it accordingly.

Create a new folder called features to keep things organized. Then create a file called profileSlice.js. We will use the createSlice function in this file to create the slice:

import { configureStore } from '@reduxjs/toolkit';
import profileReducer from '../features/profileSlice';

export const store = configureStore({
  reducer: {
    profile: profileReducer
  },
});

We will use this slice to store the user's name. Let’s go back to index.js and edit it to make the name field functional.

We want the Name field to be inactive by default, and its value should be set to the name. When we click the Change button, it should allow us to edit the field only then.

The DetailsSection component currently looks something like this.

Let's divide it into two smaller components to make it more readable and organized.

We will focus on the ProfileDetails component since it contains the Name field.

function ProfileDetails(props) {
  return (
    <div>
      <h2>Profile</h2>
      
      <label htmlFor="name">Name: </label>
      <input id="name" />
      <button>Change</button>

      <p>Posts: </p>
    </div>
  );
}

We want to use a selector from the profileSlice, namely selectName, and we also want to use the action setName. For this, we need to import the useSelector and dispatch methods from react-redux:

import { Provider, useDispatch, useSelector } from 'react-redux';

We also need to import the action and the selector from the profileSlice:

import { selectName, setName } from './features/profileSlice';

Now we will edit the ProfileDetails section to make the name field functional. The final code will look something like this.

We used a local state called nameField to make sure the input field is disabled by default and is enabled only when we click the Change button.

This is what the app should look like now:

Note: Drag from slider from the left to view the code.

By clicking 'Change' we can change the name.

Note that the state variable name in the store is updated regardless of whether we click Save or not. We can also make it so that it only updates in the store when the Save button is clicked, but it’s unnecessary. Though as a side practice, it is encouraged to try that.

question mark

Which two components does DetailsSection contain?

すべての正しい答えを選択

すべて明確でしたか?

どのように改善できますか?

フィードバックありがとうございます!

セクション 4.  4

AIに質問する

expand

AIに質問する

ChatGPT

何でも質問するか、提案された質問の1つを試してチャットを始めてください

セクション 4.  4
some-alt