0

I have below code in Login.js -

import React from 'react'
import {Button} from "reactstrap";
import 'bootstrap/dist/css/bootstrap.min.css';
import { VerifyCredentials } from "./LoginReducers/Login_Action";
import   {GlobalProvider,GlobalConsumer} from "../GlobalStore";
import { LoginReducer } from "./LoginReducers/Login_Reducers";
function Login() {
    return (
        <div>
            <GlobalConsumer>
                {
                    store=>{
                        store.dispatch(LoginReducer)
                    }
                }
            </GlobalConsumer>
            
                <form>
                <input type="text" name="txtLoginId" ></input>
                <input type="password" name="txtPassword" ></input>
                <Button color="success"></Button>
                </form>
            
            
        </div>
    )
}

export default Login

I have Login_Reducer.js-

import Axios from "axios";
import { VerifyCredentials } from "./Login_Action";

const initialState={
    userName:"",
    password:"",
    isVarified:false
}
const url='http://localhost:52016/api/values/';
export const  LoginReducer=(state=initialState,action)=>{
    switch (action.type) {
        case 'VERIFY_CREDENTIALS':
            
            Axios.get(url)
                 .then(x=>{
                     alert(x.data);

                 })
    
        default:
            break;
    }
}

How can I call store.dispatch on button click?

I tried with -

<Button color="success" onClick={() => store.dispatch({ type: 'VERIFY_CREDENTIALS' })}></Button>

But this doesnt helped

2

1 Answer 1

1

Don't write async code inside reducers,

Reducers should return an updated state you are not returning anything from reducers. In default case return existing state.

export const  LoginReducer=(state=initialState,action)=>{
    switch (action.type) {
        case 'VERIFY_CREDENTIALS':
            return {...state, ...action.payload}  
        default:
            return state;
    }
}

Component

async callAPI =() => {
    const url='http://localhost:52016/api/values/'; // move to better place
    const {data} = await Axios.get(url);
    store.dispatch({ type: 'VERIFY_CREDENTIALS', payload: data })
}

<Button color="success" onClick={callAPI}></Button>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.