简体   繁体   中英

How to update state with redux

I'm trying to build simple login form (data for authorization from API). So I have Slice for auth here is code:

auth.js

import { createSlice } from '@reduxjs/toolkit'

export const authSlice = createSlice({
    name: 'auth',
    initialState: {
        isLoggedIn: false,
        token: null,
        role: null
    },
    reducers: {
        logIn: (state) => {
            state.isLoggedIn = true
        },
        role:(state, action) =>{
            state.role = action.payload
        },
        token:(state, action) =>{
            state.token = action.payload
        },
        logOut: (state) => {
            state.isLoggedIn = false
        },
    },
})

export default authSlice.reducer;



export const { logIn, logOut, role, token } = authSlice.actions

authService.js :

import axios from 'axios';
import { api } from '../api/index'


export function authenticateUser(username, password) {

    axios
        .post(api + 'login', {username, password})
        .then(res => {
            console.log(res.headers.authorization)
        })
}

LoginForm.js

import React, { Component } from 'react';
import { Form, Col, Button } from 'react-bootstrap';
import { IoMdLogIn } from "react-icons/all";
import { authenticateUser } from '../services/authService'

export default class LoginForm extends Component{

    constructor(props) {
        super(props);
        this.state = this.initialState;
        this.credentialsChange = this.credentialsChange.bind(this);
        this.userLogin= this.userLogin.bind(this);

    }


    initialState = {
        username: '', password: ''
    }

    userLogin = (e) => {
        e.preventDefault();
        authenticateUser(this.state.username, this.state.password);
        this.setState( () => this.initialState)
    }

    credentialsChange = e => {
        this.setState({
            [e.target.name]:e.target.value
        });
    }

    render(){


        const {username, password} = this.state;

        return(
          <Form onSubmit={this.userLogin}   id="loginFormId">
              <Form.Row>
                  <Form.Group as={Col} controlId="formGridCountry">
                      <Form.Label>Username</Form.Label>
                      <Form.Control required autoComplete="off"
                                    type="text" name="username"
                                    value={username}
                                    onChange={this.credentialsChange}
                                    className={"bg-light"}
                                    placeholder="Username" />
                  </Form.Group>
              </Form.Row>
              <Form.Row>
                  <Form.Group as={Col} controlId="formGridZipCode">
                      <Form.Label>Password</Form.Label>
                      <Form.Control required autoComplete="off"
                                    type="password" name="password"
                                    value={password}
                                    onChange={this.credentialsChange}
                                    className={"bg-light"}
                                    placeholder="Password" />
                  </Form.Group>
              </Form.Row>
              <Button type="submit" variant="success">
                    <IoMdLogIn />
              </Button>
          </Form>
        );
    }

}

What I'm trying to reach is: I want to update state isLoggedIn: true after calling function authenticateUser.

I've tried to use const dispatch = useDispatch() and then calling dispatch(logIn()) but it's throwing error.

Where should I call dispatcher to update state?

You need to call the dispatcher in your AuthService.js in the api response. Check the response, if it is ok, store it. If your redux is well implemented, it will work.

 axios
        .post(api + 'login', {username, password})
        .then(res => {
            console.log(res.headers.authorization)
            //Call it here, or create a function and call it here.

        })
}

If it doesn't work, please share the error with us

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM