Here is my formSlice
and I am getting "Expression expected" after the closing brackets of the builder
and the arrow function.
import { createAsyncThunk, createReducer, createSlice } from "@reduxjs/toolkit";
import axios from "axios";
export const getform = createAsyncThunk("form/getForm", async () => {
try {
const result = await axios.get("http://localhost:5000/autoroute/");
return result.data;
} catch (error) {}
});
export const addform = createAsyncThunk("form/add", async (form) => {
try {
const result = await axios.post("http://localhost:5000/autoroute/", form);
return result.data;
} catch (error) {}
});
export const deleteform = createAsyncThunk("form/deleteForm", async (id) => {
try {
const result = await axios.delete(`http://localhost:5000/autoroute/${id}`);
return result.data;
} catch (error) {}
});
export const updateform = createAsyncThunk(
"form/deleteForm",
async ({ id, form }) => {
try {
const result = await axios.put(
`http://localhost:5000/autoroute/${id}`,
form
);
return result.data;
} catch (error) {}
}
);
createReducer(initialState, builder = {
form: [],
status: null,
});
export const formSlice = createSlice({
name: "form",
initialState,
reducers: {},
extraReducers: builder =>{
builder.getform(pending, (state) => {
state.status = "pending";
}),
builder.getform(pending, (state) => {
state.status = "success";
}),
builder.getform(pending, (state) => {
state.status = "fail";
}),
},
});
// Action creators are generated for each case reducer function
// export const { increment, decrement, incrementByAmount } = counterSlice.actions;
export default formSlice.reducer;
It says "expression expected" after the closing bracket builder
of the extraReducers
. I was working on an older version of the Redux-Toolkit but the error showed me that I need to match my code with the newer version.
2
Answers
There is quite a bit of confusing non-valida JavaScript in your code, here are relevant parts corrected:
Issue
The issue here is that you have managed to use Javascript’s Comma Operator unintentionally.
In other words, the Javascript compiler/engine is expecting another expression after the last/trailing comma.
Solution
The RTK slice’s
extraReducers
property is a function and you should either be chaining from thebuilder
object or explicitly defining each case.The
builder
object has anaddCase
function that you should be using as well,builder.getform
is not a function and would throw an error.Expected use cases:
or