I use React js hooks to fetch data from api every 10 seconds in UseEffect. The problem is that it takes 10 seconds to do the state update first.
So before the setInterval function, I need to fetch the data once the component is not rendered.
Code part is here:
function getList() {
return axios.post('http://localhost:5000/getParameters', { no: no, name: name })
.then(data => data.data)
}
function getParams() {
return axios.post('http://localhost:5000/getParametersSite', { no: no, name: name })
.then(data => data.data)
}
useEffect(() => {
let mounted = true;
let isMounted = true
const intervalId = setInterval(() => {
getParams()
.then(itemsa => {
if(mounted) {
setParams(itemsa)
}
})
getList()
.then(items => {
if(mounted) {
setMenuData(items)
}
})
}, 10000)
return () => {
clearInterval(intervalId);
isMounted = false
mounted = false;
}
}, [menuData,params])
You can use a useRefhook to know if it is the first render. like this:
const firstUpdate = useRef(true);
useEffect(() => {
let mounted = true;
let isMounted = true
if (firstUpdate.current) {
firstUpdate.current = false;
getParams()
.then(itemsa => {
if(mounted) {
setParams(itemsa)
}
})
getList()
.then(items => {
if(mounted) {
setMenuData(items)
}
})
}
const intervalId = setInterval(() => {
getParams()
.then(itemsa => {
if(mounted) {
console.log("getParams",itemsa);
setParams(itemsa)
}
})
getList()
.then(items => {
if(mounted) {
console.log("setParams",items);
setMenuData(items)
}
})
}, 10000)
return () => {
clearInterval(intervalId);
mounted = false;
}
}, [menuData,params])
like explain in react doc :
useRef returns a mutable ref object whose .current property is
initialized to the passed argument (initialValue). The returned object
will persist for the full lifetime of the component.
So no matter if your component render again.
Related
I created a class object that stores the postlist.
When the post was updated, the Pub-Sub pattern subscription function was registered.
class PostLoad extends PubSub {
store = [];
constructor (){
super();
this.connectSocket = connectSocket(this.projectUid, async (type, post) => {
console.log('Socket HOOK', type, post);
if (type === 'insert') await this.newPostPush(post);
if (type === 'update') {
const {deleted} = post;
if (deleted) await this.deletePostInStore(post.id);
}
});
}
async postLoad () {
// ...API LOAD
const value = axios.get('');
this.store = value;
}
private async newPostPush(post: HashsnapPostItem) {
if (post.type === 'video') return;
const storeItem = {...post, img: await loadImage(post.url)} as HashsnapPost;
this.store.unshift(storeItem);
if (this.store.length > this.limit) this.store.splice(this.limit);
this.emit('insert', {post: storeItem, store: this.store});
}
private deletePostInStore(targetId: number) {
this.store.push(...this.store.splice(0).filter(({id}) => id !== targetId));
this.emit('delete', {postId: targetId, store: this.store});
}
}
React component executes events registered in Pub-Sub,
When the post was updated, the status value was changed, but there was no change.
const PostList = () => {
const [postList, setPostList] = useState([]);
const postLoad = store.get('postLoad'); // PostLoad Class Object
useEffect(() => {
setPostList(postLoad.store);
}, []);
postLoad.on('delete', (payload) => {
setPostList(postLoad.store);
})
postLoad.on('insert', (payload) => {
setPostList(postLoad.store);
})
return <div>
{postList.map((post, i) => {
return <div key={`post-${i}`}></div>
})}
</div>
}
What I want is that when the Pus-Sub event is executed, the status value changes and re-rends.
async postLoad () {
// ...API LOAD- axios is a async func, need await this
const value = await axios.get('');
this.store = value;
}
postLoad.on('delete', (payload) => {
setPostList(postLoad.store);
})
postLoad.on('insert', (payload) => {
setPostList(postLoad.store);
})
// thest two register on postLoad will repeat many times, just use hook useEffect, if postLoad always change, useRef, so the right code is below
const PostList = () => {
const [postList, setPostList] = useState([]);
const {current: postLoad} = useRef(store.get('postLoad'));
useEffect(() => {
setPostList(postLoad.store);
postLoad.on('delete', (payload) => {
setPostList(postLoad.store);
})
postLoad.on('insert', (payload) => {
setPostList(postLoad.store);
})
return () => {
// please unregister delete and insert here
}
}, [postLoad]);
return <div>
{postList.map((post, i) => {
return <div key={`post-${i}`}></div>
})}
</div>
}
I am trying to learn state management with the useReducer hook so I have built a simple app that calls the pokeAPI. The app should display a random pokemon, and add more pokemons to the screen as the 'capture another' button is pressed.
However, it rerenders the component with the initialized and empty Card object before populating the Card from the axios call. I've tried at least 3 different solutions based on posts from stackoverflow.
In each attempt I have gotten the same result: the app displays an undefined card on, even though the state is updated and not undefined, it just was updated slightly after the rerendering. When clicked again that prior undefined gets properly rendered but there is now a new card displayed as undefined.
I am still getting the hang of react hooks (no pun intended!), async programming, and JS in general.
Here is the app:
https://stackblitz.com/edit/react-ts-mswxjv?file=index.tsx
Here is the code from my first try:
//index.tsx
const getRandomPokemon = (): Card => {
var randomInt: string;
randomInt = String(Math.floor(898 * Math.random()));
let newCard: Card = {};
PokemonDataService.getCard(randomInt)
.then((response) => {
//omitted for brevity
})
.catch((error) => {
//omitted
});
PokemonDataService.getSpecies(randomInt)
.then((response) => {
//omitted
})
.catch((error) => {
//omitted
});
return newCard;
};
const App = (props: AppProps) => {
const [deck, dispatch] = useReducer(cardReducer, initialState);
function addCard() {
let newCard: Card = getRandomPokemon();
dispatch({
type: ActionKind.Add,
payload: newCard,
});
}
return (
<div>
<Deck deck={deck} />
<CatchButton onClick={addCard}>Catch Another</CatchButton>
</div>
);
};
//cardReducer.tsx
export function cardReducer(state: Card[], action: Action): Card[] {
switch (action.type) {
case ActionKind.Add: {
let clonedState: Card[] = state.map((item) => {
return { ...item };
});
clonedState = [...clonedState, action.payload];
return clonedState;
}
default: {
let clonedState: Card[] = state.map((item) => {
return { ...item };
});
return clonedState;
}
}
}
//Deck.tsx
//PokeDeck and PokeCard are styled-components for a ul and li
export const Deck = ({ deck }: DeckProps) => {
useEffect(() => {
console.log(`useEffect called in Deck`);
}, deck);
return (
<PokeDeck>
{deck.map((card) => (
<PokeCard>
<img src={card.image} alt={`image of ${card.name}`} />
<h2>{card.name}</h2>
</PokeCard>
))}
</PokeDeck>
);
};
I also experimented with making the function that calls Axios a promise so I could chain the dispatch call with a .then.
//index.tsx
function pokemonPromise(): Promise<Card> {
var randomInt: string;
randomInt = String(Math.floor(898 * Math.random()));
let newCard: Card = {};
PokemonDataService.getCard(randomInt)
.then((response) => {
// omitted
})
.catch((error) => {
return new Promise((reject) => {
reject(new Error('pokeAPI call died'));
});
});
PokemonDataService.getSpecies(randomInt)
.then((response) => {
// omitted
})
.catch((error) => {
return new Promise((reject) => {
reject(new Error('pokeAPI call died'));
});
});
return new Promise((resolve) => {
resolve(newCard);
});
}
const App = (props: AppProps) => {
const [deck, dispatch] = useReducer(cardReducer, initialState);
function asyncAdd() {
let newCard: Card;
pokemonPromise()
.then((response) => {
newCard = response;
console.log(newCard);
})
.then(() => {
dispatch({
type: ActionKind.Add,
payload: newCard,
});
})
.catch((err) => {
console.log(`asyncAdd failed with the error \n ${err}`);
});
}
return (
<div>
<Deck deck={deck} />
<CatchButton onClick={asyncAdd}>Catch Another</CatchButton>
</div>
);
};
I also tried to have it call it with a side effect using useEffect hook
//App.tsx
const App = (props: AppProps) => {
const [deck, dispatch] = useReducer(cardReducer, initialState);
const [catchCount, setCatchCount] = useState(0);
useEffect(() => {
let newCard: Card;
pokemonPromise()
.then((response) => {
newCard = response;
})
.then(() => {
dispatch({
type: ActionKind.Add,
payload: newCard,
});
})
.catch((err) => {
console.log(`asyncAdd failed with the error \n ${err}`);
});
}, [catchCount]);
return (
<div>
<Deck deck={deck} />
<CatchButton onClick={()=>{setCatchCount(catchCount + 1)}>Catch Another</CatchButton>
</div>
);
};
So there are a couple of things with your code, but the last version is closest to being correct. Generally you want promise calls inside useEffect. If you want it to be called once, use an empty [] dependency array. https://reactjs.org/docs/hooks-effect.html (ctrl+f "once" and read the note, it's not that visible). Anytime the dep array changes, the code will be run.
Note: you'll have to change the calls to the Pokemon service as you're running two async calls without awaiting either of them. You need to make getRandomPokemon async and await both calls, then return the result you want. (Also you're returning newCard but not assigning anything to it in the call). First test this by returning a fake data in a promise like my sample code then integrate the api if you're having issues.
In your promise, it returns a Card which you can use directly in the dispatch (from the response, you don't need the extra step). Your onclick is also incorrectly written with the brackets. Here's some sample code that I've written and seems to work (with placeholder functions):
type Card = { no: number };
function someDataFetch(): Promise<void> {
return new Promise((resolve) => setTimeout(() => resolve(), 1000));
}
async function pokemonPromise(count: number): Promise<Card> {
await someDataFetch();
console.log("done first fetch");
await someDataFetch();
console.log("done second fetch");
return new Promise((resolve) =>
setTimeout(() => resolve({ no: count }), 1000)
);
}
const initialState = { name: "pikachu" };
const cardReducer = (
state: typeof initialState,
action: { type: string; payload: Card }
) => {
return { ...state, name: `pikachu:${action.payload.no}` };
};
//App.tsx
const App = () => {
const [deck, dispatch] = useReducer(cardReducer, initialState);
const [catchCount, setCatchCount] = useState(0);
useEffect(() => {
pokemonPromise(catchCount)
.then((newCard) => {
dispatch({
type: "ActionKind.Add",
payload: newCard
});
})
.catch((err) => {
console.log(`asyncAdd failed with the error \n ${err}`);
});
}, [catchCount]);
return (
<div>
{deck.name}
<button onClick={() => setCatchCount(catchCount + 1)}>
Catch Another
</button>
</div>
);
};
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]);
i want to add setInterval to be able to get new data from database without needing to refresh the page so i used useEffect,setInterval,useState to solve it,put intial state {refresh : false, refreshSells: null}
and there is switch when it on refresh = true and refreshSells= setinterval() but i got annoying warning
React Hook useEffect has a missing dependency: 'refreshSells'. Either include it or remove the dependency array
and if i add refreshSells it will be unstoppable loop
const Sells = () => {
const [allSells,setAllSells] = useState([])
const [refresh,setRefresh] = useState(false)
const [refreshSells , setRefreshSells] = useState(null)
const [hidden,setHidden] = useState(true)
useEffect(() => {
Axios.get('/sells')
.then(({data}) => {
setAllSells(data.sells)
})
.catch(() => {
alert('something went wrong,ask omar')
})
},[])
useEffect(() => {
if(refresh){
setRefreshSells(setInterval(() => {
Axios.get('/sells')
.then(({data}) => {
setAllSells(data.sells)
})
}, 60000));
}
else{
clearInterval(refreshSells)
}
return () => clearInterval(refreshSells)
},[refresh])
setRefreshSells updates internal state and doesn't change refreshSells during current render. So return () => clearInterval(refreshSells) will try to clear the wrong interval.
You should use useRef hook for your interval:
const refreshSellsRef = useRef(null);
...
useEffect(() => {
if(refresh){
refreshSellsRef.current = setInterval(() => {
Axios.get('/sells')
.then(({data}) => {
setAllSells(data.sells)
})
}, 60000);
return () => clearInterval(refreshSellsRef.current);
}
},[refresh])
Also note that return () => clearInterval(refreshSellsRef.current) will be called on unmount and when refresh changes. So you don't need else {clearInterval(...)}
If your business logic allows to separate the 2 effects (automatic refresh every 60s + manual refresh after clicking some button), that would simplify the code for each independent effect:
useEffect(() => {
const interval = setInterval(() => {
Axios.get('/sells')
.then(({data}) => {
setAllSells(data.sells)
})
}, 60000)
return () => clearInterval(interval)
}, [])
useEffect(() => {
if (refresh) {
setRefresh(false)
Axios.get('/sells')
.then(({data}) => {
setAllSells(data.sells)
})
};
}, [refresh])
It looks like you forgot to setRefresh(false) after triggering the refresh, but I am not sure why you needed refreshSells in the first place...
In the second useEffect you're updating the state refreshSells where useEffect expecting useCallback ref as a dependency. If you add refreshSells as a dependency to the useEffect then you may endup into memory leak issue.
So I suggest you try the below code which will solve your problem. by this you can also eliminate refreshSells
useEffect(() => {
let interval;
if (refresh) {
interval = setInterval(() => {
Axios.get('/sells')
.then(({ data }) => {
setAllSells(data.sells)
});
}, 4000);
}
return () => clearInterval(interval);
}, [refresh]);
I'm new to react and I've just started learning about hooks and context.
I am getting some data from an API with the following code:
const getScreen = async uuid => {
const res = await axios.get(
`${url}/api/screen/${uuid}`
);
dispatch({
type: GET_SCREEN,
payload: res.data
});
};
Which goes on to use a reducer.
case GET_SCREEN:
return {
...state,
screen: action.payload,
};
In Screen.js, I am calling getScreen and sending the UUID to show the exact screen. Works great. The issue I am having is when I am trying to fetch the API (every 3 seconds for testing) and update the state of nodeupdated based on what it retrieves from the API. The issue is, screen.data is always undefined (due to it being asynchronous?)
import React, {
useState,
useEffect,
useContext,
} from 'react';
import SignageContext from '../../context/signage/signageContext';
const Screen = ({ match }) => {
const signageContext = useContext(SignageContext);
const { getScreen, screen } = signageContext;
const [nodeupdated, setNodeupdated] = useState('null');
const foo = async () => {
getScreen(match.params.id);
setTimeout(foo, 3000);
};
useEffect(() => {
foo();
setNodeupdated(screen.data)
}, []);
If I remove the [] is does actually get the data from the api ... but in an infinate loop.
The thing is this seemed to work perfectly before I converted it to hooks:
componentDidMount() {
// Get screen from UUID in url
this.props.getScreen(this.props.match.params.id);
// Get screen every 30.5 seconds
setInterval(() => {
this.props.getScreen(this.props.match.params.id);
this.setState({
nodeUpdated: this.props.screen.data.changed
});
}, 3000);
}
Use a custom hook like useInterval
function useInterval(callback, delay) {
const savedCallback = useRef();
useEffect(() => {
savedCallback.current = callback;
});
useEffect(() => {
function tick() {
savedCallback.current();
}
let id = setInterval(tick, delay);
return () => clearInterval(id);
}, [delay]);
}
Then in your component
useInterval(() => {
setCount(count + 1);
}, delay);
Dan Abramov has a great blog post about this
https://overreacted.io/making-setinterval-declarative-with-react-hooks/
You can use some thing like this. Just replace the console.log with your API request.
useEffect(() => {
const interval = setInterval(() => {
console.log("Making request");
}, 3000);
return () => clearInterval(interval);
}, []);
Alternatively, Replace foo, useEffect and add requestId
const [requestId, setRequestId] = useState(0);
const foo = async () => {
getScreen(match.params.id);
setTimeout(setRequestId(requestId+1), 3000);
};
useEffect(() => {
foo();
setNodeupdated(screen.data)
}, [requestId]);