useState, speciellt för komplexa tillstånd{
"isLoading": false,
"todos": [
{
"id": 1,
"text": "Learn React",
"completed": false
},
{
"id": 2,
"text": "Learn Redux",
"completed": false
}
]
}
Exempel:
dispatch({ type: 'ADD_TODO', payload: { id: 3, text: 'Learn TypeScript', completed: false } });
{
"type": "ADD_TODO",
"payload": {
"id": 3,
"text": "Learn TypeScript",
"completed": false
}
}
const addTodo = (text: string) => {
return {
type: 'ADD_TODO',
payload: {
id: Math.random(),
text,
completed: false,
},
};
};
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'ADD_TODO':
return {
...state,
todos: [...state.todos, action.payload],
};
default:
return state;
}
};
const initialState = {
todos: [
{
id: 1,
text: 'Learn React',
completed: false,
},
{
id: 2,
text: 'Learn Redux',
completed: false,
},
],
};
const [state, dispatch] = useReducer(reducer, initialState);
type State = {
todos: Todo[];
};
type Action = { type: 'ADD_TODO'; payload: Todo }
| { type: 'TOGGLE_TODO'; payload: number };
const reducer = (state: State, action: Action) => {
};
const [state, dispatch] = useReducer(reducer, initialState);
//Exempel, not pure:
const reducer = (state: State, action: Action) => {
switch (action.type) {
case 'ADD_TODO':
state.todos.push(action.payload);
return state;
default:
return state;
}
};