Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

componentWillReceiveProps method doesn't run anymore when using redux to call api

I'm going to call api using redux: I used axios,history,react-redux,react-router-native,react-router,,redux-promise-middleware,redux-thunk component to make api call using redux: I made Reducers folder and put all my reducer file there in their own file and combine them in a main file like this this is my generateoptReducer.js file:

const initialState = {
    data: {},
    error: null,
    status: null
};
import {generateOTP} from '../Actions/api';
export default function reducer(state = initialState, action) {

    switch (action.type) {
        case (action.type === 'GENERATEOTP_PENDING' || {}).input:
            // Action is pending (request is in progress)
            return {...state, status: 'fetching',methodes:'done1'};
        case (action.type === 'GENERATEOTP_FULFILLED' || {}).input:
            // Action is fulfilled (request is successful/promise resolved)
            return {
                ...state,
                error: null,
                data: action.payload.data,
                status: 'success',
                methodes:'done1'
            };
            case 'generateOTP':
                // Action is fulfilled (request is successful/promise resolved)
                return {
                    ...state,
                    error: null,
                    data: action.payload.data,
                    status: 'success',
                    methodes:'done1'
                };
        case (action.type === 'GENERATEOTP_REJECTED' || {}).input:
            // Action is rejected (request failed/promise rejected)
            return {
                ...state,
                error: action.payload,
                status: 'error'
            };
        default:
            return state;
    }
};

And combine them in the index.js file:

import { combineReducers } from 'redux';
import { routerReducer } from 'react-router-redux';

//import api from './api-reducer';


import generateotp from './generateotpReducer';
import login from './loginReducer';

export default combineReducers({
  generateotp,
  login,
  routing: routerReducer,
});

I also made another folder named Action and put all my api in a file named api.js:

This is my above reducer action:

export const generateOTP = (phone_number) => ({
    type: 'GENERATEOTP',
    payload: axios({
        method: 'GET',
        url: format(generate_endpoint, phone_number, serviceId),
        headers: {"Accept": "application/json","Content-Type":"application/json"}
    })
});

this is also my store:

import { applyMiddleware, createStore } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import thunk from 'redux-thunk';
import promiseMiddleware from 'redux-promise-middleware';
import logger from 'redux-logger'
import reducers from './Reducers';

export default function configureStore(history) {
  const middleware = applyMiddleware(
    promiseMiddleware(),
    thunk,

    routerMiddleware(history));
  return createStore(reducers, {}, middleware);
}

and this is the way I dispatch the action: imported like this in above of my component file:

import { generateOTP } from "../Components/Actions/api";

and dispatch the action like this:

this.props.dispatch(generateOTP(formatted_phone_number));

I also connect the component like this in the bottom of the file:

export default connect(state => state)(SignIn)

Now I need the result of this api. I used to use the componentWillReceiveProps method to receive the result. I don't know why this component doesn't run. I searched too much I a find a confused result which said the state doesn't change then the componentWillReceiveProps doesn't run!!! the good thing is that the api call successfully and i can see the log and i can see the %cGENERATEOTP_PENDING and then %cGENERATEOTP_FULFILLED in the log and api call successfully but the problem is with the componentWillReceiveProps(that doesn't run any more) which I used to receive the result of the api call.

like image 285
Hussein Ojaghi Avatar asked Nov 24 '17 19:11

Hussein Ojaghi


People also ask

Is componentwillreceiveprops called before or after render?

This method is not called for the initial render. This event hook is basically componentWillReceiveProps, but worse. It happens just before render, but you can’t use this .setState (). It is useful though, because it gives you control to manipulate the component just before it receives new props or state.

What is the difference between React-Redux and @reduxjs?

React-Redux : React Redux is the official React Ui bindings layer for Redux. @reduxjs/toolkit : For writing clean redux code and it comes with most widly used Redux addons. Redux already has an async middleware function called Redux "Thunk" middleware. The thunk middleware allows us to write functions that get dispatch and getState as arguments.

What is componentwillreceiveprops event hook?

This event hook is basically componentWillReceiveProps, but worse. It happens just before render, but you can’t use this .setState (). It is useful though, because it gives you control to manipulate the component just before it receives new props or state.

What is the hooks API for React Redux?

The Hooks API: This is the newer and easier API for using React Redux. It uses React Hooks for dispatching new actions to Redux, and for accessing our application state within the Redux store. We’re going to focus on the React Redux Hooks-based API.


Video Answer


1 Answers

Your switch statement looks mailformed

case (action.type === 'GENERATEOTP_FULFILLED' || {}).input:

This will never run, because (action.type === 'GENERATEOTP_FULFILLED' || {}) will be either true, either {}, and ?.input will be always undefined

You need to write smth like this to validate some additional parameters:

switch (action.type) {
    case 'GENERATEOTP_PENDING':
        if (action.input) {
            // Action is pending (request is in progress)
            return {...state, status: 'fetching',methodes:'done1'};
        }
        break; //!
    ...
}
like image 142
Andrii Muzalevskyi Avatar answered Sep 25 '22 16:09

Andrii Muzalevskyi