Callback in Custom React Hooks - javascript

I have the following hooks:
function useLogin(state, url, loginMessage, callback) {
const history = useHistory();
const logged_in = state.user.authenticated;
useEffect(() => {
if (!logged_in) {history.push(url); loginMessage();}
else callback();
}, [logged_in])
return logged_in;
}
function useGroupAuth(state, url, loginMessage) {
const history = useHistory();
let has_group_auth = false;
state.user.available_teams.forEach(function(currentValue) {
if (currentValue.toString().toLowerCase() === teamname.toString().toLowerCase()) {
has_group_auth = true;
}
})
useEffect(() => {
if (!has_group_auth) {
if (state.user.available_teams.length != 0) {
history.push(url); loginMessage();
}
else
history.push("/"); loginMessage();
} else {
callback();
}
}, [has_group_auth])
return has_group_auth;
}
and they're used as
let loggedin = useLogin(state, "/accounts/login", teamhome2_message);
let properauth = useGroupAuth(state, ("/team/" + state.user.available_teams[0]), teamhome3_message);
useEffect(() => {
if (loggedin)
if (properauth)
checkteamexists(teamname);
}, []);
The problem is that, even though the code compiles, it's not behaving as I wanted it to. I only want if (properauth) to execute if loggedin is true.
My previous implementation worked because I was simply using callback without any custom hooks, as such:
useEffect(() => {
checklogin(function() {
checkauth(function() {
checkteamexists(teamname);
})
})
}, []);
How can I ensure that properauth won't execute unless loggedin is true, as described in the initial, hook-less useEffect hook?
Thanks in advance.

In your case, you can't update the useGroupAuth value. because it's returning only one value send one more variable(callback) to update/check whenever you need it. something like useState
Hook
function useGroupAuth(state, url, loginMessage) {
const history = useHistory();
const [has_group_auth, setAuth] = useState(false);
const validate = () => {
setAuth(
state.user.available_teams.some(
(currentValue) =>
currentValue.toString().toLowerCase() ===
teamname.toString().toLowerCase()
)
);
};
useEffect(validate, []);
useEffect(() => {
if (!has_group_auth) {
if (state.user.available_teams.length != 0) {
history.push(url);
loginMessage();
} else history.push("/");
loginMessage();
} else {
callback();
}
}, [has_group_auth]);
return [has_group_auth, validate];
}
Use
let [properauth, reValidate] = useGroupAuth(state, ("/team/" + state.user.available_teams[0]), teamhome3_message);
useEffect(() => {
if (loggedin){
// Do something
reValidate();
}
}, []);

It seems you are missing dependencies in your useEffect hook. Both loggedin and properauth (teamname as well, really) are referenced in the effect callback, so they should be included in the effect's dependencies.
const loggedin = useLogin(state, "/accounts/login", teamhome2_message);
const properauth = useGroupAuth(state, ("/team/" + state.user.available_teams[0]), teamhome3_message);
useEffect(() => {
if (loggedin && properauth && teamname) {
checkteamexists(teamname);
}
}, [loggedin, properauth, teamname]);

Related

Cant use localStorage in nextJS

I'm developing a cart system and the problem is that, when I add a product to the cart, it works in context and localStorage; but, when I refresh, the data is gone.
const dispatch = useDispatch();
const {
cartItems
} = useSelector((state) => state.cart)
const [cartState, setCartState] = useState({
cartItems: [],
})
const initialRender = useRef(true);
useEffect(() => {
if (JSON.parse(localStorage.getItem("cartState"))) {
const storedCartItems = JSON.parse(localStorage.getItem("cartState"));
setCartState([...cartItems, ...storedCartItems]);
}
}, []);
useEffect(() => {
if (initialRender.current) {
initialRender.current = false;
return;
}
window.localStorage.setItem("cartState", JSON.stringify(cartState));
}, [cartState]);
What I usually do is have some state to check against to see if the client side is loaded:
const [clientLoaded, setClientLoaded] = useState(false);
useEffect(() => {
setClientLoaded(true);
}, []);
Then anywhere you can check if clientLoaded is true, for example in another useEffect hook:
useEffect(() => {
clientLoaded && doWhatever; // do whatever you want here
}, [clientLoaded]);
Or in you render method:
{clientLoaded && <span>Render this if the client is loaded</span>}
You are earsing the value of the local storage on the first render
useEffect(() => {
if (initialRender.current) {
initialRender.current = false;
return;
}
//here
window.localStorage.setItem("cartState", JSON.stringify(cartState));
}, [cartState]);
You should :
useEffect(() => {
if (initialRender.current) {
initialRender.current = false;
} else {
window.localStorage.setItem("cartState", JSON.stringify(cartState));
}
}, [cartState]);

Way to invoke function again while not setting different value in state

So I have built app which takes value from input -> set it to the state-> state change triggers functions in useEffect (this part is in custom hook) -> functions fetch data from api -> which triggers functions in useEffect in component to store data in array. The thing is that there are two problems that I am trying to solve :
When user is putting the same value in input and setting it in state it's not triggering useEffect functions (I solved it by wrapping value in object but I am looking for better solution).
When user uses the same value in short period of time api will send the same data which again makes problem with triggering function with useEffect (I tried to solved with refresh state that you will see in code below, but it looks awful)
The question is how can I actually do it properly? Or maybe the solutions I found aren't as bad as I think they are. Thanks for your help.
component
const [nextLink, setNextLink] = useState({ value: "" });
const isMounted = useRef(false);
const inputRef = useRef(null);
const { shortLink, loading, error, refresh } = useFetchLink(nextLink);
const handleClick = () => {
setNextLink({ value: inputRef.current.value });
};
useEffect(() => {
setLinkArr((prev) => [
...prev,
{
id: prev.length === 0 ? 1 : prev[prev.length - 1].id + 1,
long: nextLink.value,
short: shortLink,
},
]);
if (isMounted.current) {
scrollToLink();
} else {
isMounted.current = true;
}
inputRef.current.value = "";
}, [refresh]);
custom hook
const useFetchLink = (linkToShorten) => {
const [shortLink, setShortLink] = useState("");
const [loading, setLoading] = useState(false);
const [error, setError] = useState("");
const [refresh, setRefresh] = useState(false);
const isMounted = useRef(false);
const fetchLink = async (link) => {
setLoading(true);
try {
const response = await fetch(
`https://api.shrtco.de/v2/shorten?url=${link}`
);
if (response.ok) {
const data = await response.json();
setShortLink(data.result.short_link);
setRefresh((prev) => !prev);
} else {
throw response.status;
}
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
useEffect(() => {
if (isMounted.current) {
if (checkLink(linkToShorten.value)) {
setError(checkLink(linkToShorten.value));
} else {
fetchLink(linkToShorten.value);
}
} else {
isMounted.current = true;
}
}, [linkToShorten]);
const value = { shortLink, loading, error, refresh };
return value;
};
export default useFetchLink;

state value does not change when using useEffect hook

well I have:
const [bgColor, setBgcolor] = useState(false);
and :
useEffect(() => {
if (window.location.pathname === '/SignUp') {
setBgcolor(true);
} else {
setBgcolor(false);
}
console.log(bgColor)
return () => {
setBgcolor(false);
}
}, [])
What I want to do : is when i reload the page or rerender the page i check the current pathname if it is equal to /Signup I set the bgColor to true but here at every time i reload give me false!
Try this:
const [bgColor, setBgcolor] = useState(false);
const { pathname } = window.location;
useEffect(() => {
if (pathname === '/SignUp') {
setBgcolor(true);
} else {
setBgcolor(false);
}
console.log(bgColor)
return () => {
setBgcolor(false);
}
}, [pathname]);

How to call a function after setting state is complete in useEffect?

I would like to run customFunction only when customEffect has finished setting isReady state. And customFunction should only run once no matter if the isReady was set to false or true as long as it was ran after it was set.
import customFunction from 'myFile';
export const smallComponent = () => {
const [isReady, setIsReady] = useState(false);
useEffect(() => {
const customEffect = async () => {
try {
const response = await get(
`some-api.com`,
);
return setIsReady(response); // response can be true or false
} catch {
return null;
}
};
customEffect();
customFunction();
}, []);
return (
<>Hello World</>
)
}
I tried to add isReady as second useEffect argument, but then my customFunction is being run before the customEffect finishes and then again after the isReady is being set.
Also tried having in a separate useEffect, but still seems to run before the customEffect finishes.
Set initial value to null and use separate useEffect as Kevin suggested (only without checking isReady true/false).
In this case setIsReady will change isReady from null to true/false and the second useEffect will be called.
import customFunction from 'myFile';
export const smallComponent = () => {
const [isReady, setIsReady] = useState(null);
useEffect(() => {
const customEffect = async () => {
try {
const response = await get(
`some-api.com`,
);
return setIsReady(response);
} catch {
return null;
}
};
customEffect();
}, []);
useEffect(() => {
if (null === isReady) {
return;
}
customFunction();
}, [isReady]);
return (
<>Hello World</>
)
}
Since you want to cue an effect to run after the isReady state is set, and the value of isReady is irrelevant you can to use a second state value to indicate the first effect and state update has completed.
This will trigger the second effect to invoke customFunction but you don't want your component to remain in this state as from here any time the component rerenders the conditions will still be met. You'll want a third "state" to indicate the second effect has been triggered. Here you can use a React ref to indicate this.
export const smallComponent = () => {
const [readySet, setReadySet] = useState(false);
const [isReady, setIsReady] = useState(false);
const customFunctionRunRef = useRef(false);
useEffect(() => {
const customEffect = async () => {
try {
const response = await get(
`some-api.com`,
);
setReadySet(true); // to trigger second effect callback
return setIsReady(response); // response can be true or false
} catch {
return null;
}
};
customEffect();
}, []);
useEffect(() => {
if (readySet && !customFunctionRunRef.current) {
// won't run before readySet is true
// won't run after customFunctionRunRef true
customFunction();
customFunctionRunRef.current = true;
}
}, [readySet]);
return (
<>Hello World</>
);
}
Better solution borrowed from #p1uton. Use null isReady state to indicate customFunction shouldn't invoke yet, and the ref to keep it from being invoked after.
export const smallComponent = () => {
const [isReady, setIsReady] = useState(null);
const customFunctionRunRef = useRef(false);
useEffect(() => {
const customEffect = async () => {
try {
const response = await get(
`some-api.com`,
);
return setIsReady(response); // response can be true or false
} catch {
return null;
}
};
customEffect();
}, []);
useEffect(() => {
if (isReady !== null && !customFunctionRunRef.current) {
// won't run before isReady is non-null
// won't run after customFunctionRunRef true
customFunction();
customFunctionRunRef.current = true;
}
}, [isReady]);
return (
<>Hello World</>
);
}
I'm not sure if I understood you correctly, but this is how I would use a separate useEffect.
import customFunction from 'myFile';
export const smallComponent = () => {
const [isReady, setIsReady] = useState(false);
useEffect(() => {
const customEffect = async () => {
try {
const response = await get(
`some-api.com`,
);
return setIsReady(response);
} catch {
return null;
}
};
customEffect();
}, []);
useEffect(() => {
if (!isReady) {
return;
}
customFunction();
}, [isReady]);
return (
<>Hello World</>
)
}
Have you tried using this package, isMounted?
I used that in my projects.
import React, { useState, useEffect } from 'react';
import useIsMounted from 'ismounted';
import myService from './myService';
import Loading from './Loading';
import ResultsView from './ResultsView';
const MySecureComponent = () => {
const isMounted = useIsMounted();
const [results, setResults] = useState(null);
useEffect(() => {
myService.getResults().then(val => {
if (isMounted.current) {
setResults(val);
}
});
}, [myService.getResults]);
return results ? <ResultsView results={results} /> : <Loading />;
};
export default MySecureComponent;
https://www.npmjs.com/package/ismounted

Have a javascript function pass a reference to itself in to another function

I found myself continuously writing the same shape of code for asynchronous calls so I tried to wrap it up in something that would abstract some of the details. What I was hoping was that in my onError callback I could pass a reference of the async function being executed so that some middleware could implement retry logic if it was necessary. Maybe this is a code smell that I'm tackling this the wrong way but I'm curious if it's possible or if there are other suggestions for handling this.
const runAsync = (asyncFunc) => {
let _onBegin = null;
let _onCompleted = null;
let _onError = null;
let self = this;
return {
onBegin(f) {
_onBegin = f;
return this;
},
onCompleted(f) {
_onCompleted = f;
return this;
},
onError(f) {
_onError = f;
return this;
},
async execute() {
if (_onBegin) {
_onBegin();
}
try {
let data = await asyncFunc();
if (_onCompleted) {
_onCompleted(data);
}
} catch (e) {
if (_onError) {
_onError(e ** /*i'd like to pass a function reference here as well*/ ** );
}
return Promise.resolve();
}
},
};
};
await runAsync(someAsyncCall())
.onBegin((d) => dispatch(something(d)))
.onCompleted((d) => dispatch(something(d)))
.onError((d, func) => dispatch(something(d, func)))
.execute()
I'm thinking you could use a custom hook. Something like -
import { useState, useEffect } from 'react'
const useAsync = (f) => {
const [state, setState] =
useState({ loading: true, result: null, error: null })
const runAsync = async () => {
try {
setState({ ...state, loading: false, result: await f })
}
catch (err) {
setState({ ...state, loading: false, error: err })
}
}
useEffect(_ => { runAsync() }, [])
return state
}
Now we can use it in a component -
const FriendList = ({ userId }) => {
const response =
useAsync(UserApi.fetchFriends(userId)) // <-- some promise-returning call
if (response.loading)
return <Loading />
else if (response.error)
return <Error ... />
else
return <ul>{response.result.map(Friend)}</ul>
}
The custom hook api is quite flexible. The above approach is naive, but we can think it through a bit more and make it more usable -
import { useState, useEffect } from 'react'
const identity = x => x
const useAsync = (runAsync = identity, deps = []) => {
const [loading, setLoading] = useState(true)
const [result, setResult] = useState(null)
const [error, setError] = useState(null)
useEffect(_ => {
Promise.resolve(runAsync(...deps))
.then(setResult, setError)
.finally(_ => setLoading(false))
}, deps)
return { loading, error, result }
}
Custom hooks are dope. We can make custom hooks using other custom hooks -
const fetchJson = (url = "") =>
fetch(url).then(r => r.json()) // <-- stop repeating yourself
const useJson = (url = "") => // <-- another hook
useAsync(fetchJson, [url]) // <-- useAsync
const FriendList = ({ userId }) => {
const { loading, error, result } =
useJson("some.server/friends.json") // <-- dead simple
if (loading)
return <Loading .../>
if (error)
return <Error .../>
return <ul>{result.map(Friend)}</ul>
}

Categories