Skip to content
Advertisement

How to use redux state data in a link?

I am new to redux and reactjs. I am trying to use a state data called type in the link I am fetching using axios in line no 17. I am setting the value of type from another .jsx file using dispatch().

Here in Home.jsx file I am calling dispatch in line no 24 for updating the state value type with onClick event.

Home.jsx

import React from 'react';
import '../styles/home.scss';
import { Link } from 'react-router-dom';
import { setType } from '../redux/imageSlice';
import { useDispatch } from 'react-redux';

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

  return (
    <div className="container">
      <div className="row">
        <div className="col-sm-6 col-md-4 d-flex justify-content-center my-3">
          <div className="ci">
            <img
              className="img-fluid"
              src="https://res.cloudinary.com/djz3p8sux/image/upload/v1662295247/web-projects-images/natures_hodrkk.jpg"
              alt="Nature"
            />
            <Link to="/nature">
              <div className="middle">
                <div
                  className="text"
                  onClick={() => dispatch(setType('nature'))}>
                  Nature
                </div>
              </div>
            </Link>
          </div>
        </div>
      </div>
    </div>
  );
};

export default Home;

imageSlice.js

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

const initialState = {
  type: '',
  images: [],
  error: null,
  isLoading: false,
};

const config = {
  Authorization: '563492ad6f91700001000001350d302e175b4c208aac413953d6edcc',
};

export const fetchImages = createAsyncThunk('images/fetchImages', async () => {
  const res = await axios.get(
    `https://api.pexels.com/v1/search?query=${initialState.type}&per_page=15`,
    {
      headers: config,
    }
  );
  return res.data;
});

export const imageSlice = createSlice({
  name: 'images',
  initialState,
  reducers: {
    setType: (state, action) => {
      state.type = action.payload;
    },
  },
  extraReducers: builder => {
    builder.addCase(fetchImages.pending, state => {
      state.isLoading = true;
    });
    builder.addCase(fetchImages.fulfilled, (state, action) => {
      state.isLoading = false;
      state.images = action.payload;
      state.error = null;
    });
    builder.addCase(fetchImages.rejected, (state, action) => {
      state.isLoading = false;
      state.images = [];
      state.error = action.error.message;
    });
  },
});

export const { setType } = imageSlice.actions;

export default imageSlice.reducer;

store.js

import { configureStore } from '@reduxjs/toolkit';
import imageReducer from './imageSlice';

export const store = configureStore({
  reducer: {
    images: imageReducer,
  },
});

How to do that? I am trying to update the fetching link using state type value on line 17 in imageSlice.js file.

Advertisement

Answer

One option is to provide the type to fetchImages by parameters (see payload):

export const fetchImages = createAsyncThunk('images/fetchImages', async (payload) => {
  const res = await axios.get(
    `https://api.pexels.com/v1/search?query=${payload.type}&per_page=15`,
    {
      headers: config,
    }
  );
  return res.data;
});

Then you need to provide the type to the function, when calling fetchImages. Here in an example component:

import { fetchImages } from '../redux/imageSlice';
import { useDispatch, useSelector } from 'react-redux';

function YourCallingComponent(props) {
    const dispatch = useDispatch();
    const currentType = useSelector((state) => state.type);

    function fetchImagesOfType() {
        dispatch(fetchImages({
            type: currentType
        }));
    }
    
    return (
    ...
    )
}
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement