Data Fetching
  • 08 Mar 2024
  • 1 Minute to read
  • Dark
    Light
  • PDF

Data Fetching

  • Dark
    Light
  • PDF

Article summary

Writing Redux code

The scaffold includes Redux and Redux Toolkit configured out of the box.

You can export slice objects in a default export of your module.

A slice object is made of the properties reducer and actions.

Redux Toolkit includes createSlice, a helper API creating slices that simplifies the implementations of reducers and action creators.

The following is an example that tracks the number of presses made on the “share” message button.

import { createSlice } from "@reduxjs/toolkit"

export const slice = createSlice({
  name: "share",
  initialState: {
    count: 0
  },
  reducers: {
    increment(state) {
      state.count++
    }
  }
})

You can get the state of this module with useSelector command, as shown:

  const { count } = useSelector(state => state.Share)

Important

Notice that this piece of state is nested within the state tree on the Share property.  All modules get their own key within the root state tree that is named after the (capitalized) name of the module directory.


Was this article helpful?