You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
83 lines
2.3 KiB
83 lines
2.3 KiB
// redux/actions/moveAction.ts
|
|
|
|
import { FETCH_MOVES } from '../constants';
|
|
import { Move } from "../../entities/Move";
|
|
import { Dispatch } from "redux";
|
|
import { API_BASE_URL } from "../../config";
|
|
import { RootState } from "../store";
|
|
|
|
export const setMoves = (moves: Move[]) => {
|
|
return {
|
|
type: FETCH_MOVES,
|
|
payload: moves,
|
|
};
|
|
}
|
|
|
|
export const createMove = (move: Move) => {
|
|
return async (dispatch: Dispatch) => {
|
|
try {
|
|
const response = await fetch(`${API_BASE_URL}/move`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(move),
|
|
});
|
|
const data = await response.json();
|
|
dispatch(setMoves(data));
|
|
}
|
|
catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
}
|
|
|
|
export const getMoves = () => {
|
|
return async (dispatch: Dispatch) => {
|
|
try {
|
|
const response = await fetch(`${API_BASE_URL}/move`);
|
|
const data = await response.json();
|
|
dispatch(setMoves(data));
|
|
}
|
|
catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
}
|
|
|
|
export const updateMove = (id: string, move: Move) => {
|
|
return async (dispatch: Dispatch, getState: () => RootState) => {
|
|
try {
|
|
const response = await fetch(`${API_BASE_URL}/move/${id}`, {
|
|
method: 'PUT',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
},
|
|
body: JSON.stringify(move),
|
|
});
|
|
const updatedMove = await response.json();
|
|
const moves = getState().move.moves.map((m: Move) => m.id === id ? updatedMove : m);
|
|
dispatch(setMoves(moves));
|
|
}
|
|
catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
}
|
|
|
|
export const deleteMove = (id: string) => {
|
|
return async (dispatch: Dispatch, getState: () => RootState) => {
|
|
try {
|
|
await fetch(`${API_BASE_URL}/move/${id}`, {
|
|
method: 'DELETE',
|
|
});
|
|
const moves = getState().move.moves.filter((m: Move) => m.id !== id);
|
|
dispatch(setMoves(moves));
|
|
}
|
|
catch (error) {
|
|
console.error(error);
|
|
}
|
|
}
|
|
}
|
|
|