evaldschukin
evaldschukin

Reputation: 29

How to dispatch to store from a file that isn't imported anywhere and returns nothing

I just started with React-Redux and I decided to put such action as axios request in a separate file:

import React, { useEffect } from "react";
import { useDispatch } from "react-redux";
import axios from "axios";

const GetRequest = () => {
  const dispatch = useDispatch();

  async function fetchData() {
    try {
      const commits = await axios.get(`url`
      );
      const commitsData = await commits.data;
      dispatch({ type: "GET_REQUEST", payload: { commitsData } });
    } catch (err) {
      await console.log(err);
    }
  }

  useEffect(() => {
    fetchData();
  }, []);

  return <div></div>;
};

export default GetRequest;

But how i can dispatch this if my store and react app can't see this file .How to correctly declare the store about the existence of this file.(Because the option with rendering this file in App.js seems terribly wrong to me)

Upvotes: 1

Views: 322

Answers (1)

0x6368656174
0x6368656174

Reputation: 992

The best way is to use thunk for this logic and dispatch thunk.

import { createAsyncThunk } from '@reduxjs/toolkit';
import axios from 'axios';

// Define thunk somewhere
export const getRequest = createAsyncThunk('getRequest', async (payload: string, thunkAPI) => {
  try {
    const commits = await axios.get(payload);
    const commitsData = await commits.data;
    thunkAPI.dispatch({ type: 'GET_REQUEST', payload: { commitsData } });
  } catch (err) {
    console.log(err);
  }
});

import React, { useEffect } from 'react';
import { useDispatch } from 'react-redux';

// Use thunk in your code
export function SomeComponent() {
  const dispatch = useDispatch();

  useEffect(() => {
    dispatch(getRequest('https://example.com'));
  }, []);

  return <div />;
}

Upvotes: 1

Related Questions