useReducer Hook Sample

by Admin 27. January 2020 10:27

Store.tsx

import React from "react";

interface IState {
episodes: [];
favorites: [];
}

const initialState: IState = {
episodes: [],
favorites: []
};
export const Store = React.createContext<IState>(initialState);

function reducer() {
//todo
}

export function StoreProvider(props: any) {
return <Store.Providervalue={initialState}>{props.children}</Store.Provider>;
}

App.tsx

import React from "react";
import "./styles.css";

function App(): JSX.Element {
const reducer = (state, action) => {
switch (action) {
case "Add":
return state + 1;
case "Sub":
return state - 1;
case "Res":
return (state = 0);
default:
return state;
}
};
//similar to useState
//const [value, setValue] = React.useState('')
const [count, dispatch] = React.useReducer(reducer, 0);

return (
<>
<div>{count}</div>
<button onClick={() =>dispatch("Add")}>+</button>
<button onClick={() =>dispatch("Sub")}>-</button>
<button onClick={() =>dispatch("Res")}>Reset</button>
</>
);
}

export default App;

 

Index.tsx

import React from "react";
import ReactDOM from "react-dom";
import { StoreProvider } from "./store";
import App from "./App";
const rootElement = document.getElementById("root");
ReactDOM.render(
<StoreProvider>
<App/>
</StoreProvider>,
rootElement
);

 

Store.tsx

import React from 'react'

interface IState{

episodes : [];

favorites : [];

};

const initialState : IState => {

episodes : [],

favorites : []

};

 

export const Store = React.createContext<IState>(initialState);

 

export function StoreProvider(props: any)

{

return <Store.Provider value = {initialState}>{props.children}</Store.Provider>

}

App.tsx

import React from 'react';

 function App()

{

 //Like useState

 const [count, dispatch] = React.useReducer(reducer, 0);

const reducer = (state, action) =>

{

 switch(action)

 {

   case 'Add' : return state+1;

   case 'Sub' : return state-1;

   case 'Res' : return state=0;

   default: return state;

 }

}

 

return (

<div>

{count}

<button onClick = { ()=> dispatch('Add') }>+</button>

<button onClick = { ()=> dispatch('Sub')}>-</button>

<button onClick = { ()=> dispatch('Res')}>Res</button>

</div>

);

}

export default App;

 

index.tsx

import React from 'react'

import ReactDom fom 'react-dom'

import Store from '/Store'

import App from '/App'

 

const rootElement = document.getElementById('root');

ReactDom.render

(<StoreProvider>

<App />

</StoreProvider>,

rootElement);

Tags:

Comments are closed

TextBox

Tag cloud

    RecentPosts