Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

access store data from one slice to another slice in redux toolkit to pass custom param in API

Profile Slice:

import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { IMAGE_API, ACCESS_KEY } from "../../app/utils/constant";

export const getImages = createAsyncThunk('images', async () => {
  return fetch(`${IMAGE_API + ACCESS_KEY}`).then((res) =>
    res.json()
  )
})
console.log(IMAGE_API + ACCESS_KEY);

const ProfilePicSlice = createSlice({
  name: 'imageList',
  initialState: {
    images: [],
    loading: false,
  },
  extraReducers:  (builder) => {
    builder.addCase(getImages.pending, (state) => {
      state.loading = true;
    })
    builder.addCase(getImages.fulfilled, (state, action) => {
      state.loading = false;
      state.images.push(action.payload);
      console.log(action.payload)
    })
    builder.addCase(getImages.rejected, (state) => {
      state.loading = true;
    })
  }
});

export default ProfilePicSlice.reducer

Form Slice:

import { createSlice } from "@reduxjs/toolkit";

const initialState = []

const UserSlice = createSlice({
  name: 'users',
  initialState,
  reducers: {
    addUser: (state, action) => {
      state.push(action.payload);
    }
  }
});

export const {addUser} = UserSlice.actions;
export default UserSlice.reducer;

I want to add custom param in API URL in asyncThunk ‘${IMAGE_API + ‘custom param’ + ACCESS_KEY}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

custom param should come from form slice data.

>Solution :

redux-toolkit async thunks are able to access the ThunkAPI, which includes a function to get the current redux state object, it is the second argument passed to the thunk callback. From here you can select the state value you need.

See PayloadCreator.

Example:

export const getImages = createAsyncThunk(
  'imageList /images',
  (_, { getState }) => {
    const store = getState();

    const param = state.users./* access into state to get property */;

    return fetch(`${IMAGE_API}${param}${ACCESS_KEY}`)
      .then((res) => res.json());
  }
);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading