0

I'm new to React and didn't understand why below functional component is getting called 3 times while fetching data from github api

useFetchJobs.js

below file makes call to github job api and fetches data

Here I have console.log(state.jobs); which shows 3 outputs namely

  1. []

  2. undefined

  3. (50) { }

import { useReducer, useEffect } from 'react';
import axios from 'axios';

const ACTIONS = {
    MAKE_REQUEST: 'make-request',
    GET_DATA: 'get-data',
    ERROR: 'error',
}

const proxyurl = "https://cors-anywhere.herokuapp.com/";

const BASE_URL = 'https://jobs.github.com/positions.json';

function reducer(state, action) {
    switch (action.type) {
        case ACTIONS.MAKE_REQUEST:
            return { loading: true, job: [] }
        case ACTIONS.GET_DATA:
            return { ...state, loading: false, jobs: action.payload.jobs }
        case ACTIONS.ERROR:
            return { ...state, loading: false, error: action.payload.error, jobs: [] }
        default:
            return state;
    }
}


export default function useFetchJobs(params, page) {
    //hook
    const [state, dispatch] = useReducer(reducer, { jobs: [], loading: true })

    //hook
    useEffect(() => {
        const cancelToken = axios.CancelToken.source();

        dispatch({ type: ACTIONS.MAKE_REQUEST })

        axios.get(proxyurl + BASE_URL, {
            cancelToken: cancelToken.token,
            params: { markdown: true, page: page, ...params }
        }).then(res => {
            dispatch({ type: ACTIONS.GET_DATA, payload: { jobs: res.data } })
        }).catch(e => {
            if (axios.isCancel(e)) return
            dispatch({ type: ACTIONS.ERROR, payload: { error: e } })
        })

        return () => {
            cancelToken.cancel();
        }

    }, [params, page])

    console.log(state.jobs);

    return state;
}

APP.js

below file takes data returned from functional component, checks its length and outputs it to screen

import React from 'react';
import { Container } from 'react-bootstrap';

import useFetchJobs from './useFetchJobs.js';

function App() {

  const { jobs, loading, error } = useFetchJobs();


  return (
    <Container>
      {loading && <h1>Loading...</h1>}
      {error && <h1>Error - Reload Again</h1>}
      <h1>{jobs ? '' : '50'}</h1>
    </Container>
  )

}

export default App;

I see 3 output against console.log(state.jobs); inside useFetchJobs.js file

enter image description here

vikramvi
  • 3,312
  • 10
  • 45
  • 68

1 Answers1

1
  1. [] -> this because when you initially call the useFetchJobs.

  2. undefined -> this because of typo return { loading: true, job: [] } => return { loading: true, jobs: [] }

  3. (50) { } -> this when the state updates.