Multiple useEffect and setState causing callback to be called twice - reactjs

I'm test driving a pattern I found online known as meiosis as an alternative to Redux using event streams. The concept is simple, the state is produced as a stream of update functions using the scan method to evaluate the function against the current state and return the new state. It works great in all of my test cases but when I use it with react every action is called twice. You can see the entire app and reproduce the issue at CodeSandbox.
import state$, { actions } from "./meiosis";
const App = () => {
const [todos, setTodos] = useState([]);
const [newTodo, setNewTodo] = useState({
title: "",
status: "PENDING"
});
useEffect(() => {
state$
.pipe(
map(state => {
return state.get("todos")
}),
distinctUntilChanged(),
map(state => state.toJS())
)
.subscribe(state => setTodos(state));
}, []);
useEffect(() => {
state$
.pipe(
map(state => state.get("todo")),
distinctUntilChanged(),
map(state => state.toJS())
)
.subscribe(state => setNewTodo(state));
}, []);
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
{genList(todos)}
<div className="formGroup">
<input
type="text"
value={newTodo.title}
onChange={evt => actions.typeNewTodoTitle(evt.target.value)}
/>
<button
onClick = {() => {
actions.addTodo()
}}
>
Add TODO
</button>
<button
onClick={() => {
actions.undo();
}}
>UNDO</button>
</div>
</header>
</div>
);
};
Meisos
import { List, Record } from "immutable";
import { Subject } from "rxjs";
const model = {
initial: {
todo: Record({
title: "",
status: "PENDING"
})(),
todos: List([Record({ title: "Learn Meiosis", status: "PENDING" })()])
},
actions(update) {
return {
addTodo: (title, status = "PENDING") => {
update.next(state => {
console.log(title);
if (!title) {
title = state.get("todo").get("title");
}
const todo = Record({ title, status })();
return state.set("todos", state.get("todos").push(todo));
});
},
typeNewTodoTitle: (title, status = "PENDING") => {
update.next(state => {
return state.set("todo", Record({ title, status })())
});
},
resetTodo: () => {
update.next(state =>
state.set("todo", Record({ title: "", status: "PENDING" })())
);
},
removeTodo: i => {
update.next(state => state.set("todos", state.get("todos").remove(i)));
}
};
}
}
const update$ = new BehaviorSubject(state => state) // identity function to produce initial state
export const actions = model.actions(update$);
export default update$;

Solve my problem. It stemmed from a misunderstanding of how RXJS was working. An issue on the RxJS github page gave me the answer. Each subscriptions causes the observable pipeline to be re-evaluated. By adding the share operator to the pipeline it resolves this behavior.
export default update$.pipe(
scan(
(state, updater) =>
updater(state),
Record(initial)()
),
share()
);

Related

Best way to use useMemo/React.memo for an array of objects to prevent rerender after edit one of it?

I'm struggling with s performance issue with my React application.
For example, I have a list of cards which you can add a like like facebook.
Everything, all list is rerendering once one of the child is updated so here I'm trying to make use of useMemo or React.memo.
I thought I could use React.memo for card component but didn't work out.
Not sure if I'm missing some important part..
Parent.js
const Parent = () => {
const postLike= usePostLike()
const listData = useRecoilValue(getCardList)
// listData looks like this ->
//[{ id:1, name: "Rose", avararImg: "url", image: "url", bodyText: "text", liked: false, likedNum: 1, ...etc },
// { id:2, name: "Helena", avararImg: "url", image: "url", bodyText: "text", liked: false, likedNum: 1, ...etc },
// { id: 3, name: "Gutsy", avararImg: "url", image: "url", bodyText: "text", liked: false, likedNum: 1, ...etc }]
const memoizedListData = useMemo(() => {
return listData.map(data => {
return data
})
}, [listData])
return (
<Wrapper>
{memoizedListData.map(data => {
return (
<Child
key={data.id}
data={data}
postLike={postLike}
/>
)
})}
</Wrapper>
)
}
export default Parent
usePostLike.js
export const usePressLike = () => {
const toggleIsSending = useSetRecoilState(isSendingLike)
const setList = useSetRecoilState(getCardList)
const asyncCurrentData = useRecoilCallback(
({ snapshot }) =>
async () => {
const data = await snapshot.getPromise(getCardList)
return data
}
)
const pressLike = useCallback(
async (id) => {
toggleIsSending(true)
const currentList = await asyncCurrentData()
...some api calls but ignore now
const response = await fetch(url, {
...blabla
})
if (currentList.length !== 0) {
const newList = currentList.map(list => {
if (id === list.id) {
return {
...list,
liked: true,
likedNum: list.likedNum + 1,
}
}
return list
})
setList(newList)
}
toggleIsSending(false)
}
},
[setList, sendYell]
)
return pressLike
}
Child.js
const Child = ({
postLike,
data
}) => {
const { id, name, avatarImg, image, bodyText, likedNum, liked } = data;
const onClickPostLike = useCallback(() => {
postLike(id)
})
return (
<Card>
// This is Material UI component
<CardHeader
avatar={<StyledAvatar src={avatarImg} />}
title={name}
subheader={<SomeImage />}
/>
<Image drc={image} />
<div>{bodyText}</div>
<LikeButton
onClickPostLike={onClickPostLike}
liked={liked}
likedNum={likedNum}
/>
</Card>
)
}
export default Child
LikeButton.js
const LikeButton = ({ onClickPostLike, like, likedNum }) => {
const isSending = useRecoilValue(isSendingLike)
return (
<Button
onClick={() => {
if (isSending) return;
onClickPostLike()
}}
>
{liked ? <ColoredLikeIcon /> : <UnColoredLikeIcon />}
<span> {likedNum} </span>
</Button>
)
}
export default LikeButton
The main question here is, what is the best way to use Memos when one of the lists is updated. Memorizing the whole list or each child list in the Parent component, or use React.memo in a child component...(But imagine other things could change too if a user edits them. e.g.text, image...)
Always I see the Parent component is highlighted with React dev tool.
use React.memo in a child component
You can do this and provide a custom comparator function:
const Child = React.memo(
({
postLike,
data
}) => {...},
(prevProps, nextProps) => prevProps.data.liked === nextProps.data.liked
);
Your current use of useMemo doesn't do anything. You can use useMemo as a performance optimization when your component has other state updates and you need to compute an expensive value. Say you have a collapsible panel that displays a list:
const [expand, setExpand] = useState(true);
const serverData = useData();
const transformedData = useMemo(() =>
transformData(serverData),
[serverData]);
return (...);
useMemo makes it so you don't re-transform the serverData every time the user expands/collapses the panel.
Note, this is sort of a contrived example if you are doing the fetching yourself in an effect, but it does apply for some common libraries like React Apollo.

React hooks: Update an object value within an array in state

What's the best approach to update the values of objects within an array in the state? Can't really wrap my head around hooks yet. The class approach seems to be way clearer for me at least in this case
In the below situation I'd like to change the active value on click to false within the object and also add a date value of when that happened.
handleChangeStatus doesn't work at all, I just get the 'test' on click, no errors.
const App = () => {
const [tasks, setTasks] = useState([
{
text: 'Example 1',
id: 1,
urgent: true,
targetDate: '2021-07-16',
active: true,
finishDate: null,
},
{
text: 'Example 2',
id: 2,
urgent: false,
targetDate: '2021-06-03',
active: false,
finishDate: null,
},
{
text: 'Example 3',
id: 3,
urgent: false,
targetDate: '2021-07-16',
active: true,
finishDate: null,
},
]);
const handleChangeStatus = (id) => {
console.log('test');
const newArr = [...tasks];
newArr.forEach((task) => {
if (task.id === id) {
console.log(task.id);
task.active = false;
task.finishDate = new Date().getTime();
}
});
setTasks(newArr);
};
return (
<div className="App">
<AddTask />
<TaskList tasks={tasks} changeStatus={handleChangeStatus} />
</div>
);
};
TaskList
const TaskList = (props) => {
const active = props.tasks.filter((task) => task.active);
const done = props.tasks.filter((task) => !task.active);
const activeTasks = active.map((task) => (
<Task key={task.id} task={task} changeStatus={props.changeStatus} />
));
const doneTasks = done.map((task) => <Task key={task.id} task={task} />);
return (
<>
<h3>Active Tasks ({active.length})</h3>
<ul>{activeTasks}</ul>
<hr />
<h3>Done Tasks ({done.length})</h3>
<ul>{doneTasks}</ul>
</>
);
};
Task
const Task = (props) => {
const { text, id, urgent, targetDate, active } = props.task;
const style = { color: 'red' };
if (active) {
return (
<p>
<strong style={urgent ? style : null}>{text}</strong>, id: {id}, target
date: {targetDate} <button onClick={props.changeStatus}>Done</button>
</p>
);
} else {
return (
<p>
<strong style={urgent ? style : null}>{text}</strong>, id: {id}, target
date: {targetDate}
</p>
);
}
};
<button onClick={props.changeStatus}>Done</button>
You are sending event object to the function, try sending id
<button onClick={() => props.changeStatus(id)}>Done</button>
Per the React Docs
If the new state is computed using the previous state, you can pass a function to setState. The function will receive the previous value, and return an updated value.
so you could do something like:
const handleChangeStatus = (id) => {
console.log('test');
setTask((prev)=>prev.map((task)=>{
if(task.id === id){
return {...task,active: false, finishDate: new Date().getTime()}
}
else{
return task;
}
})
}

What is causing the following Firestore error in ReactJS? Function DocumentReference .update() called with invalid data. Unsupported field value:

There seems to be something wrong with the way I update state, as it gets overwritten...
import Servis from "./funkc/servisni";
import React, { useState, useEffect } from "react";
export default function ContactUpdate(props) {
const initialState = {
ime: props.item.Ime,
prezime: props.item.Prezime,
datum: props.item.Datum,
kontakt: props.item.Kontakt,
published: props.item.Published,
id: props.Id,
};
const [theItem, setTheItem] = useState();
const [message, setMessage] = useState();
useEffect(() => {
setTheItem(props.item);
console.log(theItem);
}, []);
const handleInputChange = (event) => {
const { name, value } = event.target;
setTheItem({ ...theItem, [name]: value });
console.log(theItem, props.Id);
};
the problem seems to be in the following:
const updateItem = (theItem) => {
let data = {
Ime: theItem.Ime,
Prezime: theItem.Prezime,
Kontakt: theItem.Kontakt,
Datum: theItem.Datum,
Published: true,
Id: theItem.id,
};
Servis.update(theItem.id, data)
.then(() => {
setMessage("Uspjesno ste izmijenili unos!");
})
.catch((e) => {
console.log(e);
});
};
as visible in the console.log
return (
<div className="container">
{console.log(("theItem", props.Id, theItem))}
{theItem ? (
<div className="edit-form">
<h4>Kontakt</h4>
...
<button type="submit" onClick={updateItem}>
Update
</button>
<p>{message}</p>
</div>
) : (
<div>
<br />
<p>Odaberi jedan broj...</p>
</div>
)}{" "}
</div>
);
}
The call on the updateItem function by clicking on the 'Update' button results in the error : Function DocumentReference .update() called with invalid data. Unsupported field value...
Resolved through being careful about naming variables...
</div>
<ContactUpdate item={item} id={theId} />
</div>
and then
const updateItem = () => {
let data = {
Ime: theItem.Ime,
Prezime: theItem.Prezime,
Kontakt: theItem.Kontakt,
Datum: theItem.Datum,
published: true,
id: props.id,
};
Servis.update(props.id, data)
.then(() => {
setMessage("Uspjesno ste izmijenili unos!");
})
.catch((e) => {
console.log(e);
});
};

have problem with react useEffect function

I have this update form for a place and I fetch its data from the backend to add initial inputs in useEffect but I got this error
Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in a useEffect cleanup function.
I know the problem is related to unmounted the component before update the state but I try many solutions but not working. Anyone have an idea how to fix that
const UpdatePlace = () => {
const placeId = useParams().pId;
const [loadedPlace, setLoadedPlace] = useState();
// const [isLoading, setIsLoading] = useState(true);
const { error, sendRequest, clearError } = useHttpClient();
const [isLoading, formState, inputHandler, setFormData] = useForm(
{
title: {
value: "",
isValid: false,
},
description: {
value: "",
isValid: false,
},
},
true
);
useEffect(() => {
const fetchPlace = async () => {
try {
const res = await sendRequest(`/api/places/${placeId}`);
await setLoadedPlace(res.data.place);
setFormData(
{
title: {
value: res.data.place.title,
isValid: true,
},
description: {
value: res.data.place.description,
isValid: true,
},
},
true
);
} catch (err) {}
};
fetchPlace();
}, [sendRequest, placeId, setFormData]);
if (!loadedPlace && !error) {
return (
<div className="center" style={{ maxWidth: "400px", margin: "0 auto" }}>
<Card>
<h2>No place found!</h2>
</Card>
</div>
);
}
const placeUpdateSubmitHandler = (e) => {
e.preventDefault();
console.log(formState.inputs, formState.isFormValid);
};
return (
<>
{isLoading ? (
<LoadingSpinner asOverlay />
) : error ? (
<ErrorModal error={error} onClear={clearError} />
) : (
<>
<Title label="Update place" />
<form className="place-form" onSubmit={placeUpdateSubmitHandler}>
<Input
element="input"
type="text"
id="title"
label="Update title"
validators={[VALIDATOR_REQUIRE()]}
errorText="please enter valid title"
onInput={inputHandler}
initialValue={loadedPlace.title}
initialValid={true}
/>
<Input
element="textarea"
id="description"
label="Update description"
validators={[VALIDATOR_REQUIRE(), VALIDATOR_MINLENGTH(5)]}
errorText="please enter valid description (min 5 chars) "
onInput={inputHandler}
initialValue={loadedPlace.description}
initialValid={true}
/>
<Button type="submit" disabled={!formState.isFormValid}>
Update place
</Button>
</form>
</>
)}
</>
);
};
You can use useEffect with [] with cleanup function, as it will execute last one like this:
useEffect(() => {
return () => {
console.log('cleaned up');
}
},[])
This error means that your request completes after you have navigated away from that page and it tries to update a component that is already unmounted. You should use an AbortController to abort your request. Something like this should work:
useEffect(() => {
const controller = new AbortController();
const signal = controller.signal;
const fetchPlace = async () => {
try {
const res = await fetch(`/api/places/${placeId}`, { signal }).then(response => {
return response;
}).catch(e => {
console.warn(`Fetch 1 error: ${e.message}`);
});
await setLoadedPlace(res.data.place);
setFormData(
{
title: {
value: res.data.place.title,
isValid: true,
},
description: {
value: res.data.place.description,
isValid: true,
},
},
true
);
} catch (err) {}
};
fetchPlace();
return () => {
controller.abort();
};
}, [sendRequest, placeId, setFormData]);
Edit: Fix undefined obj key/value on render
The above warning will not stop your component from rendering. What would give you an undefined error and prevent your component from rendering is how you initiate the constant loadedPlace. You initiate it as null but you use it as an object inside your Input initialValue={loadedPlace.title}. When your component tries to do the first render it reads the state for that value but fails to locate the key and breaks.
Try this to fix it:
const placeObj = {
title: {
value: '',
isValid: true,
},
description: {
value: '',
isValid: true,
};
const [loadedPlace, setLoadedPlace] = useState(placeObj);
Always make sure that when you use an object you don't use undefined keys upon render.

How to use axios in Effect Hook?

In class based Component:
componentDidMount() {
axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
this.setState({
posts: res.data.slice(0, 10)
});
console.log(posts);
})
}
I tried this:
const [posts, setPosts] = useState([]);
useEffect(() => {
axios.get('https://jsonplaceholder.typicode.com/posts').then((res) => {
setPosts(res.data.slice(0, 10));
console.log(posts);
})
});
It creates an infinite loop. If I pass a []/{} as the second argument[1][2], then it blocks further call. But it also prevents the array from updating.
[1] Infinite loop in useEffect
[2] How to call loading function with React useEffect only once
Giving an empty array as second argument to useEffect to indicate that you only want the effect to run once after the initial render is the way to go. The reason why console.log(posts); is showing you an empty array is because the posts variable is still referring to the initial array, and setPosts is also asynchronous, but it will still work as you want if used in the rendering.
Example
const { useState, useEffect } = React;
function App() {
const [posts, setPosts] = useState([]);
useEffect(() => {
setTimeout(() => {
setPosts([{ id: 0, content: "foo" }, { id: 1, content: "bar" }]);
console.log(posts);
}, 1000);
}, []);
return (
<div>{posts.map(post => <div key={post.id}>{post.content}</div>)}</div>
);
}
ReactDOM.render(<App />, document.getElementById("root"));
<script src="https://unpkg.com/react#16.7.0-alpha.0/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom#16.7.0-alpha.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>
You can check how axios-hooks is implemented.
It's super simple and uses the config object (or url) you provide to decide when to make a request, and when not to, as explained in Tholle's answer.
In addition to allowing you to use the awesome axios in your stateless functional components, it also supports server side rendering, which - it turns out - hooks make very straightforward to implement.
Disclaimer: I'm the author of that package.
I've written a Custom Hooks for Axios.js.
Here's an example:
import React, { useState } from 'react';
import useAxios from '#use-hooks/axios';
export default function App() {
const [gender, setGender] = useState('');
const {
response,
loading,
error,
query,
} = useAxios({
url: `https://randomuser.me/api/${gender === 'unknow' ? 'unknow' : ''}`,
method: 'GET',
options: {
params: { gender },
},
trigger: gender,
filter: () => !!gender,
});
const { data } = response || {};
const options = [
{ gender: 'female', title: 'Female' },
{ gender: 'male', title: 'Male' },
{ gender: 'unknow', title: 'Unknow' },
];
if (loading) return 'loading...';
return (
<div>
<h2>DEMO of <span style={{ color: '#F44336' }}>#use-hooks/axios</span></h2>
{options.map(item => (
<div key={item.gender}>
<input
type="radio"
id={item.gender}
value={item.gender}
checked={gender === item.gender}
onChange={e => setGender(e.target.value)}
/>
{item.title}
</div>
))}
<button type="button" onClick={query}>Refresh</button>
<div>
{error ? error.message || 'error' : (
<textarea cols="100" rows="30" defaultValue={JSON.stringify(data || {}, '', 2)} />
)}
</div>
</div>
);
}
You can see the result online.

Resources