0

HI I am trying to implement fake API in my react redux demo application when I fire event I am getting response twice I don't no where I did wrong here I am sharing my code please review it

User.tsx

import React, { useState } from 'react';

import { useDispatch, useSelector } from "react-redux";
import { RootState } from "./Store";
import { GetUser } from './actions/UserActions';

function User() {
    const dispatch = useDispatch();
    const [userName, setUserName] = useState("");
    const userState = useSelector((state: RootState) => state.user);
    const handleChange = (event: React.ChangeEvent<HTMLInputElement>) => setUserName(event.target.value);
    const handleSubmit = () => dispatch(GetUser(userName));

    return (
        <div >
            <input type="text" onChange={handleChange} />
            <button onClick={handleSubmit}>Search</button>
        </div>
    );
}

export default User;

UserActions.tsx

import { Dispatch } from "redux"
import {
  UserDispatchTypes,
  // UserType,
  USER_FAIL,
  USER_LOADING,
  USER_SUCCESS,
} from "./UserActionTypes"
import axios from "axios"

export const GetUser = (user: string) => async (
  dispatch: Dispatch<UserDispatchTypes>
) => {
  try {
    dispatch({
      type: USER_LOADING,
    })
    console.log("USer Action load")
    
    const articleAPI = "https://reqres.in/api/articles"
    
   const article = { title: "React Hooks POST Request Example" }
    

    
    const res1 = await axios.post(
      articleAPI,
      article 
      // , {
    )
    console.log(res1.data, "res1 response")
    dispatch({
      type: USER_SUCCESS,

      payload: res1.data,
    })
  } catch (e) {
    dispatch({
      type: USER_FAIL,
    })
  }
}

UserREducer

import {
  UserDispatchTypes,
  UserType,
  USER_FAIL,
  USER_LOADING,
  USER_SUCCESS,
} from "../actions/UserActionTypes"


interface DefaultStateI {
  loading: boolean
  user?: UserType
}

const defaultState: DefaultStateI = {
  loading: false,
}

const userReducer = (
  state = defaultState,
  action: UserDispatchTypes
): DefaultStateI => {
  switch (action.type) {
    case USER_FAIL:
      return {
        ...state,
        loading: false,
      }
    case USER_LOADING:
      return {
        ...state,
        loading: true,
      }
    case USER_SUCCESS:
      return {
        ...state,
        loading: false,
        user:res1.data
      }
    default:
      return state
  }
}

export default userReducer

UseerActionTypes

export const USER_LOADING = 'USER_LOADING'
export const USER_FAIL = 'USER_FAIL'
export const USER_SUCCESS = 'USER_SUCCESS'

export type UserType = { userData: UserAbility[] }


export type UserAbility = {
    user: {
        name: string

        mobile_No: number
    }
}
export interface UserLoading {
    type: typeof USER_LOADING
}

export interface UserFail {
    type: typeof USER_FAIL
}

export interface UserSuccess {
    type: typeof USER_SUCCESS,
    payload: UserType
}

export type UserDispatchTypes = UserLoading | UserFail | UserSuccess

code are working fine but when i see browser console api call twice

  • how many "res1 response" do you have in console log. Sometime with CORS policy, browser will call the 1st api (OPTION) to get permission. if success, it will call real api. They is same url – san Oct 07 '20 at 09:39
  • HI San there is one res1 response i am getting in console. now please tell me how do I resolve this issue ? – stackoverflow0071 Oct 07 '20 at 10:15
  • You check two request. If two request have same url and the first method api is OPTION and the second method api is GET, this is Preflighted requests. Ref: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS – san Oct 07 '20 at 10:27
  • Hi maybe this post can help you : https://stackoverflow.com/questions/47948008/react-redux-counter-example-action-firing-twice – Virgile Junique Oct 07 '20 at 10:32
  • Btw i advise you to try redux promise middleware like redux-thunk or saga to be able to "auto" manage pending / success / failure request state and all you async call :) – Virgile Junique Oct 07 '20 at 10:33

0 Answers0