Implementing TanStack Store Mutations
Example of converting a Redux action that updates the server state (through API call) into a TanStack mutation, handling success and failure scenarios.
import { createStore } from 'tanstack-store-react';
// Define the initial state
const initialState = {
serverState: null,
isLoading: false,
error: null
};
// Create the store
export const store = createStore({
initialState,
actions: {
updateServerStateStart: (state) => {
state.isLoading = true;
state.error = null;
},
updateServerStateSuccess: (state, newServerState) => {
state.serverState = newServerState;
state.isLoading = false;
},
updateServerStateFailure: (state, error) => {
state.isLoading = false;
state.error = error;
}
}
});
This code snippet initializes the TanStack Store with an initial state representing the server state, and defines actions for handling the start, success, and failure of updating the server state.
import { store } from './pathToYourStore';
import axios from 'axios';
// Function to perform the API call and dispatch actions
export const updateServerState = async (dispatch, serverData) => {
dispatch(store.actions.updateServerStateStart());
try {
const response = await axios.post('/api/updateServerState', serverData);
dispatch(store.actions.updateServerStateSuccess(response.data));
} catch (error) {
dispatch(store.actions.updateServerStateFailure(error.message));
}
};
This function performs an asynchronous API call to update the server state. It dispatches actions to handle the loading state, successful update with the new server state, and any errors.