Home > Back-end >  I'm confused about the callback function in react js
I'm confused about the callback function in react js

Time:01-18

I followed the react js tutorial, and the code is written like this

import React, { Fragment, useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import { ArticleListSection } from "../../components";
import { ArticlesCard, Hero } from "../../components/molecules";
import { setDataBlog } from "../../config/redux/action";

export const Home = () => {
  const { dataBlog } = useSelector((state) => state.homeReducer);
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(setDataBlog());
  }, [dispatch]);
  return (
    <Fragment>
      <Hero
        titleHero="Kemal is a place to write, read, and connect."
        descHero="It's easy and free to post your thinking on any topic and connect
      with millions of readers."
        button="Start Writing!"
      ></Hero>
      <ArticlesCard dataBlog={dataBlog}></ArticlesCard>;
      <ArticleListSection dataBlog={dataBlog}></ArticleListSection>
    </Fragment>
  );
};
export default Home;

the other part is called like this (homeAction.js)

import Axios from "axios";

export const setDataBlog = () => (dispatch) => {
  console.log({ dispatch });
  Axios.get("http://localhost:4000/v1/blog/posts")
    .then((result) => {
      const responseAPI = result.data;
      dispatch();
    })
    .catch((err) => {
      console.log("error: ", err);
    });
};

What I understand, is that dispatch is a function of useDispatch and it is passed as a parameter in the form of a function setDataBlog().

so if i destucturing the homeAction will be like this

export const setDataBlog = () =>{
  return(dispatch)=>{
    Axios.get("http://localhost:4000/v1/blog/posts")
      .then((result) => {
        const responseAPI = result.data;
        dispatch({ type: "UPDATE_DATA_BLOG", payload: responseAPI.data });
      })
      .catch((err) => {
        console.log("error: ", err);
      });
  }
}

BUT I'm confused,

  • what is returned from the dispatch
  • I know that the 2 arrow function in homeAction.js file is a function that returns another function but why is it written like that.
  • in the setDataBlog function there is another "dispatch" parameter, where does this parameter come from??!!
  • why in setDataBlog function he calls dispatch function again??? isn't it the dispatch function that calls setDataBlog, how can call parent function inside child function?!!!

Anyway thank you if you answering this question.

CodePudding user response:

enter image description here.

to understand this issue we need to get closer to the material

  1. arrow functions
  2. curried function
  3. callbacks

And I will answer my questions

  1. I know that the 2 arrow function in homeAction.js file is a function that returns another function but why is it written like that.

to understand this maybe we should start from a simple syntax like this:

middleWare = callBack => {
  callBack("Ini pesan dari middleware");
}

fungsi2 = pesan=>{
    document.write(pesan)
}

const container = () => {
  middleWare(fungsi2)
}

container()

think of middleWare as our dispatch, and fungsi2 as our setDataBlog. From the simple callback function above, we will get output on our browser screen "Ini pesan dari middle ware!".

furthermore, what if we actually have a function inside a function like this:

fungsi2 = () => pesan=>{
    document.write(pesan)
}

how do we print the text? the way we print it is by calling the function like this:

const container = () => {
  middleWare(fungsi2())
}

okay we are getting closer to the answer to our question. now what if we make the parameter in our callback a variable?

middleWare = callBack => {
  const action = "ini output callback"
  callBack(action);
}

fungsi2 = () => pesan =>{
    document.write(pesan)
}

const container = () => {
  middleWare(fungsi2())
}

container()

wow it can! means we can dispatch functions also inside this middleware. okay let's pass the function into the callback

middleWare = callBack => {
  const fungsiBerupaOutput = (text) =>{
    document.write(text)
  }
  callBack(fungsiBerupaOutput)
}

fungsi2 = () => fungsi =>{
    fungsi("halo")
}

const container = () => {
  middleWare(fungsi2())
}

container()

now we can print the hello text to the screen from the fungsi parameter.

In conclusion, unknown parameters are sent from the middleware so we can print them.

Hope it helps for people who are just learning Java Script!

Reference:

  1. https://www.w3schools.com/js/js_arrow_function.asp
  2. https://www.petanikode.com/javascript-fungsi/
  3. https://www.petanikode.com/javascript-output/
  4. https://www.geeksforgeeks.org/what-is-the-use-of-middleware-redux-thunk/
  • Related