Code Monkey home page Code Monkey logo

react-redux-example's Introduction

Redux

App component tree without redux

before_redux

App component tree with redux

after_redux

Create a slice using js

  1. Create a feature file describing the slice name.

    touch feature/assignmentSlice.js
  2. Define an initial state.

    const initialState = {
        showActions: false,
        assignmentId: null
    }
  3. Define the name, initialState and reducers from the slice.

    import { createSlice } from '@reduxjs/toolkit'
    
    const assignmentSlice = createSlice({
        name: 'assignmentTable',
        initialState,
        reducers: {
            show: (state, action) => {
                state.showActions = true
                state.assignmentId = context.payload
            },
            hide: (state) => {
                state.showActions = false
            }
        }
    })
  4. Export the slice actions.

    export const { hide, show } = assignmentSlice.actions
  5. Export the slice reducer.

    export default assignmentSlice.reducer
  6. Add the reducer to the store.reducer definition.

    import assignmentSliceReducer from './feature/assignmentSlice'
    
    const store = configureStore({
        reducer: {
            assignment: assignmentSliceReducer
        }
    })

Using a slice

  1. Read the state.
    import { useSelector } from 'react-redux'
    
    const MyComponent = () => {
        const showActions = useSelector((state) => state.assignment.showActions)
    
        return <p> The showActions value is {showActions}</p>
    }
    
    export default MyComponent
  2. Call actions.
    import { useDispatch } from 'react-redux'
    import { show, hide } from './feature/assignmentSlice'
    
    const MyComponent = () => {
        const dispatch = useDispatch()
    
        return (
            <>
                <button onClick={() => dispatch(show(1))}>Show with payload</button>
                <button onClick={() => dispatch(hide())}>Hide</button>
            </>
        )    
    }
    
    export default MyComponent

Typescript considerations

  • Ensure to create a type or interface for the initial state of your slice.
interface InitialState {
    showActions: boolean,
    assignmentId: number|null
}
  • Define the payload typein your createSlice.reducer definition:
import { createSlice, PayloadAction } from '@reduxjs/toolkit'

const assignmentSlice = createSlice({
    /*...*/
    reducers: {
        show: (state, action: PayloadAction<number>) => {
            state.showActions = true
            state.assignmentId = context.payload
        }
    }
})
  • When you export your store, ensure to define the root state type, it can be easily done by inferring it
    const store = configureStore({/*...*/})
    export type RootState = ReturnType<typeof store.getState>
    export type AppDispatch = typeof store.dispatch
  • Use the root types to have autocompletion
import React from 'react'
import { useSelector } from 'react-redux'
import { RootState } from '../store'

const MyComponent = () => {
  const showActions = useSelector((state: RootState) => state.tableAction.showActions)
    /*...*/
}

export default MyComponent

Run the example project

  • Clone the repository.
  • Move to the directory.
  • Install the dependencies.
    npm i
  • Run the start script.
    npm run start

react-redux-example's People

Contributors

javleds avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.