UseReducer hook doesn't update state (Can't perform a React state update on an unmounted component) - react-hooks

I'm trying to use useReducer instead of useState in a custom hook that loads the initial data from the API, and getting an error updating a state. (I use useReducer here for learning purposes).
The component fetches data firstly correctly, the error occurs when I update the state (book/edit/delete interview).
I left the previous useState code in the comments for better understanding.
import { useReducer, useEffect } from "react";
import axios from "axios";
const SET_DAY = "SET_DAY";
const SET_APPLICATION_DATA = "SET_APPLICATION_DATA";
const SET_INTERVIEW = "SET_INTERVIEW";
const reducer = (state, action) => {
switch (action.type) {
case SET_DAY:
return { ...state, day: action.day }
case SET_APPLICATION_DATA:
return {
...state,
days: action.days,
appointments: action.appointments,
interviewers: action.interviewers
}
case SET_INTERVIEW: {
return { ...state, id: action.id, interview: action.interview }
}
default:
throw new Error();
}
}
export default function useApplicationData() {
// const [state, setState] = useState({
// day: "Monday",
// days: [],
// appointments: {},
// interviewers: {}
// });
const initialState = {
day: "Monday",
days: [],
appointments: {},
interviewers: {}
};
const [state, dispatch] = useReducer(reducer, initialState);
//updates the spots remaining when book/edit/cancel interview
const updateSpots = (requestType) => {
const days = state.days.map(day => {
if(day.name === state.day) {
if (requestType === 'bookInterview') {
// return { ...day, spots: day.spots - 1 }
return dispatch({ type: SET_DAY, spots: day.spots - 1 });
}else {
// return { ...day, spots: day.spots + 1 }
return dispatch({ type: SET_DAY, spots: day.spots + 1 });
}
}
// return { ...day };
return dispatch({ type: SET_DAY, spots: day.spots });
});
return days;
}
//sets the current day data
// const setDay = day => setState(prev => ({ ...prev, day }));
const setDay = (day) => dispatch({ type: SET_DAY, day });
//adds new interview data to database
const bookInterview = (id, interview) => {
const appointment = { ...state.appointments[id] };
const bookOrEdit = appointment.interview ? 'edit' : 'book'; //defines the request type
appointment.interview = { ...interview };
const appointments = { ...state.appointments, [id]: appointment };
let days = state.days;
if (bookOrEdit === 'book') {
days = updateSpots('bookInterview');
}
return axios
.put(`/api/appointments/${id}`, {interview})
.then(() => {
//setState({ ...state, appointments, days });
dispatch({ type: SET_INTERVIEW, id, interview });
})
};
//deletes interview data from database
const cancelInterview = (id) => {
const appointment = {...state.appointments[id], interview: null};
const appointments = {...state.appointments, [id]: appointment };
const days = updateSpots();
return axios
.delete(`/api/appointments/${id}`)
.then(() => {
//setState({ ...state, appointments, days });
dispatch({ type: SET_INTERVIEW, id, interview: null });
})
};
useEffect(() => {
let isMounted = false;
Promise.all([
axios.get('/api/days'),
axios.get('/api/appointments'),
axios.get('/api/interviewers')
])
.then((all) => {
// setState(prev => ({
// ...prev,
// days: all[0].data,
// appointments: all[1].data,
// interviewers: all[2].data}));
// });
if (!isMounted) {
console.log("done!");
}
isMounted = true;
dispatch({ type: SET_APPLICATION_DATA, days: all[0].data, appointments: all[1].data, interviewers:all[2].data });
});
}, []);
return { state, setDay, bookInterview, cancelInterview }
};
I'd be appreciated for pointing me in the right direction on what I'm doing wrong. Thank you!

Related

how to prevent api call from redux toolkit because its calling everytime on comp renders

ProfilePic.js
Due to useeffect on each component rendering API call happen.
How to solve this issue?
useEffect(() => {
dispatch(getImages())
}, [dispatch])
The API call is happening in ProfilePicSlice.js file below:
or how to add if condition in if condition, refer below code
ProfilePicSlice.js
import { createSlice, createAsyncThunk } from '#reduxjs/toolkit'
import { IMAGE_API, ACCESS_KEY } from "../../app/utils/constant";
export const getImages = createAsyncThunk('imageList/images',
(_, { getState }) => {
const store = getState();
const topic = store.users[0].topic;
const otherTopic = store.users[0].otherTopic;
if(store === null){
console.log('api call')
}else{
console.log('no api call')
}
if(topic === 'Other'){
return fetch(`${IMAGE_API}${otherTopic}${ACCESS_KEY}`)
.then((res) => res.json());
}else{
return fetch(`${IMAGE_API}${topic}${ACCESS_KEY}`)
.then((res) => res.json());
}
})
const ProfilePicSlice = createSlice({
name: 'imageList',
initialState: {
images: [],
selectedImage: {},
loading: false,
},
extraReducers: (builder) => {
builder.addCase(getImages.fulfilled, (state, action) => {
state.loading = false;
state.images.push(action.payload);
console.log(action.payload)
})
},
reducers: {
selectedImage: (state, action) => {
state.selectedImage = action.payload;
},
removeImage: (state, action) => {
const itemId = action.payload;
state.images = state.images.filter((item) => item.id !== itemId);
}
},
});
export const { selectedImage, removeImage } = ProfilePicSlice.actions
export default ProfilePicSlice.reducer

Providing two combined Reducers for my redux saga store prevents my websocket channel message from triggering, but only one does not?

Configured my store this way with redux toolkit for sure
const rootReducer = combineReducers({
someReducer,
systemsConfigs
});
const store = return configureStore({
devTools: true,
reducer: rootReducer ,
// middleware: [middleware, logger],
middleware: (getDefaultMiddleware) => getDefaultMiddleware({ thunk: false }).concat(middleware),
});
middleware.run(sagaRoot)
And thats my channel i am connecting to it
export function createSocketChannel(
productId: ProductId,
pair: string,
createSocket = () => new WebSocket('wss://somewebsocket')
) {
return eventChannel<SocketEvent>((emitter) => {
const socket_OrderBook = createSocket();
socket_OrderBook.addEventListener('open', () => {
emitter({
type: 'connection-established',
payload: true,
});
socket_OrderBook.send(
`subscribe-asdqwe`
);
});
socket_OrderBook.addEventListener('message', (event) => {
if (event.data?.includes('bids')) {
emitter({
type: 'message',
payload: JSON.parse(event.data),
});
//
}
});
socket_OrderBook.addEventListener('close', (event: any) => {
emitter(new SocketClosedByServer());
});
return () => {
if (socket_OrderBook.readyState === WebSocket.OPEN) {
socket_OrderBook.send(
`unsubscribe-order-book-${pair}`
);
}
if (socket_OrderBook.readyState === WebSocket.OPEN || socket_OrderBook.readyState === WebSocket.CONNECTING) {
socket_OrderBook.close();
}
};
}, buffers.expanding<SocketEvent>());
}
And here's how my saga connecting handlers looks like
export function* handleConnectingSocket(ctx: SagaContext) {
try {
const productId = yield select((state: State) => state.productId);
const requested_pair = yield select((state: State) => state.requested_pair);
if (ctx.socketChannel === null) {
ctx.socketChannel = yield call(createSocketChannel, productId, requested_pair);
}
//
const message: SocketEvent = yield take(ctx.socketChannel!);
if (message.type !== 'connection-established') {
throw new SocketUnexpectedResponseError();
}
yield put(connectedSocket());
} catch (error: any) {
reportError(error);
yield put(
disconnectedSocket({
reason: SocketStateReasons.BAD_CONNECTION,
})
);
}
}
export function* handleConnectedSocket(ctx: SagaContext) {
try {
while (true) {
if (ctx.socketChannel === null) {
break;
}
const events = yield flush(ctx.socketChannel);
const startedExecutingAt = performance.now();
if (Array.isArray(events)) {
const deltas = events.reduce(
(patch, event) => {
if (event.type === 'message') {
patch.bids.push(...event.payload.data?.bids);
patch.asks.push(...event.payload.data?.asks);
//
}
//
return patch;
},
{ bids: [], asks: [] } as SocketMessage
);
if (deltas.bids.length || deltas.asks.length) {
yield putResolve(receivedDeltas(deltas));
}
}
yield call(delayNextDispatch, startedExecutingAt);
}
} catch (error: any) {
reportError(error);
yield put(
disconnectedSocket({
reason: SocketStateReasons.UNKNOWN,
})
);
}
}
After Debugging I got the following:
The Thing is that when I Provide one Reducer to my store the channel works well and data is fetched where as when providing combinedReducers I am getting
an established connection from my handleConnectingSocket generator function
and an empty event array [] from
const events = yield flush(ctx.socketChannel) written in handleConnectedSocket
Tried to clarify as much as possible
ok so I start refactoring my typescript by changing the types, then saw all the places that break, there was a problem in my sagas.tsx.
Ping me if someone faced such an issue in the future

Vue3 composition API refactor computed favoritesRecipes

I am new to composition API with vue3. I have created that computed property and I would like to have that computed variable in a different file, I'm not sure if I should create a new component or I could achieve it from a js file.
Here is the component working (I did it with setup()):
export default {
name: "Recipes",
setup() {
const state = reactive({
recipes: [],
sortBy: "alphabetically",
ascending: true,
searchValue: "",
});
const favoritesRecipes = computed(() => {
let tempFavs = state.recipes;
// Show only favorites
if (state.heart) {
tempFavs = tempFavs.filter(item => {
return item.favorite;
});
}
return tempFavs;
...
});
...
}
return {
...toRefs(state),
favoriteRecipes
}
// end of setup
}
You can split it into two files
state.js
export const state = reactive({
recipes: [],
sortBy: "alphabetically",
ascending: true,
searchValue: "",
});
export const favoriteRecipes = computed(() => {
let tempFavs = state.recipes;
// Show only favorites
if (state.heart) {
tempFavs = tempFavs.filter(item => {
return item.favorite;
});
}
return tempFavs;
})
and recipes.vue
import { state, favoriteRecipes } from "state.js";
export default {
name: "Recipes",
setup() {
return {
...toRefs(state),
favoriteRecipes,
};
},
};
But this will make the state persistent, so if you have multiple components, they will all have the same favoriteRecipes and state values.
If you want them to be unique for each component...
state.js
export const withState = () => {
const state = reactive({
recipes: [],
sortBy: "alphabetically",
ascending: true,
searchValue: "",
});
const favoriteRecipes = computed(() => {
let tempFavs = state.recipes;
// Show only favorites
if (state.heart) {
tempFavs = tempFavs.filter((item) => {
return item.favorite;
});
}
return tempFavs;
});
return { state, favoriteRecipes };
};
and recipes.vue
import { withState } from "state.js";
export default {
name: "Recipes",
setup() {
const {state, favoriteRecipes} = withState()
return {
...toRefs(state),
favoriteRecipes,
};
},
};

How to write an action that updates Redux's store?

I have a web app where use React-Redux. There is React table (list) that I need to populate with data from database. I use WebApi on the server and automatically generated (by TypeWriter) web-api on the client. The key parts of code looks as following:
1) Routing:
<Route path="/Dictionary/:dictionaryName" component={Dictionary} />
2) State:
export type SingleDictionaryState = Readonly<{
singleDictionary: WebApi.SingleDictionary[];
}>;
export const initialState: SingleDictionaryState = {
singleDictionary: [],
};
3) Reducer:
export const reducer: Reducer<SingleDictionaryState> = (state: SingleDictionaryState = initialState, action: AllActions): SingleDictionaryState => {
switch (action.type) {
case getType(actions.setSingleDictionaryValue):
return { ...state, ...action.payload };
}
return state;
};
4) Actions:
const actionsBasic = {
setSingleDictionaryValue: createAction('singleDictionary/setSingleDictionaryValue', (singleDictionary: any) => singleDictionary),
};
const actionsAsync = {
getDictionaryByName: (dictionaryName: string) => {
const currentState = store.getState().singleDictionary;
WebApi.api.dictionaryQuery.getDictionary(capitalizeForApi(dictionaryName));
},
};
export const actions = Object.assign(actionsBasic, actionsAsync);
const returnsOfActions = Object.values(actionsBasic).map($call);
export type AllActions = typeof returnsOfActions[number];
5) Container:
const mapStateToProps = (state: AppState, ownProps: OwnProps): StateProps => ({
dictionaryType: state.singleDictionary,
});
const mapDispatchToProps = (dispatch: Dispatch<any>): DispatchProps => ({
onLoad: (dictionaryName: string) => {
Actions.singleDictionary.getDictionaryByName(dictionaryName);
},
});
export default withRouter(connect<StateProps, DispatchProps, OwnProps>(mapStateToProps, mapDispatchToProps)(DictionaryPage));
6) The client web-api:
class DictionaryQueryService {
getDictionary(name: string) {
const user = store.getState().oidc.user;
const headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
headers.append('Cache-Control', 'no-cache, no-store, must-revalidate');
headers.append('Pragma', 'no-cache');
headers.append('Expires', '0');
if (user) {
headers.append('Authorization', `Bearer ${user.access_token}`);
}
return () => {
return fetch(`api/dictionaries/${encodeURIComponent(name)}`, {
method: 'get',
headers,
})
.then(response => {
if (!response.ok) {
const traceId = response.headers.get("X-Trace-Id");
throw new ApiError(`${response.status} ${response.statusText}`, traceId);
}
return response.status == 204 ? null : response.json() as Promise<any[]>;
});
};
}
Actually, I'm not sure how to write my getDictionaryByName action.
Just my 2 cents. I use ES6 syntax, but Typescript would work as similar way.
actionTypes.js
export const RESET_DICTIONARIES = 'RESET_DICTIONARIES';
export const LOAD_DICTIONARIES_REQUEST = 'LOAD_DICTIONARIES_REQUEST';
export const LOAD_DICTIONARIES_REQUEST_SUCCESS = 'LOAD_DICTIONARIES_REQUEST_SUCCESS';
export const LOAD_DICTIONARIES_REQUEST_FAILURE = 'LOAD_DICTIONARIES_REQUEST_FAILURE';
dictionaryActions.js
/* Load Dictionariies*/
export function loadDictionariesRequestBegin() {
return {type: types.LOAD_DICTIONARIES_REQUEST};
}
export function loadDictionariesRequest(name) {
return function(dispatch) {
dispatch(loadDictionariesRequestBegin());
// eslint-disable-next-line no-undef
const request = new Request(`${YOUR_URL}/api/dictionaries/{name}`, {
method: 'get',
headers: new Headers({
'Content-type': 'application/json',
'Accept': 'application/json',
'Authorization': auth.getToken(),
})
});
return fetch(request)
.then(
response => {
if (!response.ok) {
dispatch(loadDictionariesRequestFailure(response.statusText));
throw new Error(response.statusText);
}
return response.json();
},
error => {
dispatch(loadDictionariesRequestFailure(error));
throw error;
})
.then(dictionaries=> {
if (dictionaries) {
dispatch(loadDictionariesRequestSuccess(dictionaries));
return dictionaries;
} else {
throw new Error('dictionaries NOT found in response');
}
});
};
}
export function loadDictionariesRequestSuccess(dictionaries) {
return {type: types.LOAD_DICTIONARIES_REQUEST_SUCCESS, dictionaries};
}
export function loadDictionariesRequestFailure(error) {
return {type: types.LOAD_DICTIONARIES_REQUEST_FAILURE, error};
}
dictionaryReducer.js
export default function dictionaryReducer(state = initialState.dictionaries, action) {
switch (action.type) {
case types.RESET_DICTIONARIES:
return {
...state,
loaded: false,
loading: false,
error: null,
};
/* load dictionaries*/
case types.LOAD_DICTIONARIES_REQUEST:
return {
...state,
error: null,
loaded: false,
loading: true
};
case types.LOAD_DICTIONARIES_REQUEST_SUCCESS:
return {
...state,
data: action.dictionaries,
error: null,
loaded: true,
loading: false
};
case types.LOAD_DICTIONARIES_REQUEST_FAILURE:
return {
...state,
loaded: false,
loading: false,
error: action.error
};
return state;
}
initialState.js
export default {
actions: {},
dictionaries: {
data: [],
loaded: false,
loading: false,
error: null,
},
}
dictionary client side API
this.props.actions
.loadDictionaryRequest(name)
.then(data => {
this.setState({ data: data, errorMessage: '' });
})
.then(() => {
this.props.actions.resetDictionaries();
})
.catch(error => {
...
});
Hope this may help.

Graphql-js subscriptions unit tests not working as expected

I have written integration tests for graphql-js subscriptions, which are showing weird behavior.
My graphq-js subscription works perfectly in GraphiQL. But when the same subscriptions is called from unit test, it fails.
Ggraphql-Js object, with resolve function and subscribe function
return {
type: outputType,
args: {
input: {type: new GraphQLNonNull(inputType)},
},
resolve(payload, args, context, info) {
const clientSubscriptionId = (payload) ? payload.subscriptionId : null;
const object = (payload) ? payload.object : null;
var where = null;
var type = null;
var target = null;
if (object) {
where = (payload) ? payload.object.where : null;
type = (payload) ? payload.object.type : null;
target = (payload) ? payload.object.target : null;
}
return Promise.resolve(subscribeAndGetPayload(payload, args, context, info))
.then(payload => ({
clientSubscriptionId, where, type, target, object: payload.data,
}));
},
subscribe: withFilter(
() => pubSub.asyncIterator(modelName),
(payload, variables, context, info) => {
const subscriptionPayload = {
clientSubscriptionId: variables.input.clientSubscriptionId,
remove: variables.input.remove,
create: variables.input.create,
update: variables.input.update,
opts: variables.input.options,
};
subscriptionPayload.model = model;
try {
pubSub.subscribe(info.fieldName, null, subscriptionPayload);
} catch (ex) {
console.log(ex);
}
return true;
}
),
};
Subscription query
subscription {
Customer(input: {create: true, clientSubscriptionId: 112}) {
customer {
id
name
age
}
}
}
Mutation query
mutation {
Customer {
CustomerCreate (input:{data:{name:"Atif 50", age:50}}) {
obj {
id
name
}
}
}
}
Integration Test
'use strict';
const ws = require('ws');
const { SubscriptionClient } = require('subscriptions-transport-ws');
const { ApolloClient } = require('apollo-client');
const { HttpLink } = require('apollo-link-http');
const { InMemoryCache } = require('apollo-cache-inmemory');
const Promise = require('bluebird');
const expect = require('chai').expect;
const chai = require('chai').use(require('chai-http'));
const server = require('../server/server');
const gql = require('graphql-tag');
let apollo;
let networkInterface;
const GRAPHQL_ENDPOINT = 'ws://localhost:5000/subscriptions';
describe('Subscription', () => {
before(async () => {
networkInterface = new SubscriptionClient(
GRAPHQL_ENDPOINT, { reconnect: true }, ws);
apollo = new ApolloClient({
networkInterface ,
link: new HttpLink({ uri: 'http://localhost:3000/graphql' }),
cache: new InMemoryCache()
});
});
after(done => {
networkInterface.close() ;
});
it('subscription', async () => {
const client = () => apollo;
// SUBSCRIBE and make a promise
const subscriptionPromise = new Promise((resolve, reject) => {
client().subscribe({
query: gql`
subscription {
Customer(input: {create: true,
clientSubscriptionId: 112,
options: {where: {age: 50}}}) {
customer {
name
}
}
}
`
}).subscribe({
next: resolve,
error: reject
});
});
let execGraphQL;
// MUTATE
await execGraphQL(
`mutation {
Customer {
CustomerCreate (input:{data:{name:"Atif 21", age:50}}) {
obj {
id
name
}
}
}
}`
);
// ASSERT SUBSCRIPTION RECEIVED EVENT
expect(await subscriptionPromise).to.deep.equal({});
});
});
Issue Here
When test in run, payload in the resolve function contains global data, where as it should contain the subscription payload. So the code breaks.

Resources