I'm working on a simple quiz application and want to dispatch an action (called FreeResponseSubmit) to store the user's input (called searchField) into the answers object and then reset the form field. I've tried to chain promises, and while the answers object is updated with the user's input the second "then" doesn't work as planned (I'm assuming the response from the previous promise isn't usable), and the searchField value is never reset.
Are promises even the right way to go on this or is async/await a better route? I've been racking my brain for some time trying to figure this out (still new to these frameworks) so any help is greatly appreciated.
free-response.component:
handleClick(){
const searchFieldPromise= new Promise((resolve, reject)=>{
resolve(this.state.searchField);
});
searchFieldPromise.then((searchField)=>this.props.freeResponseSubmit(searchField))
.then((value)=>this.setState({searchField:""}));
}
The logic within the handleClick method can actually be simplified into this:
const { searchField } = this.state;
const { freeResponseSubmit } = this.props;
freeResponseSubmit(searchField);
this.setState({
searchField:''
});
This is because the action for freeResponseSubmit would have already taken in the value from your component's state, thus carrying out any subsequent operations within redux. Therefore, you can just clear the component's state.
Related
I have run into this weird behavior which I don't know how to figure out. It involves array destructuring. I know that react renders changes on state only when a new object is passed into the setLocations function, even though it doesn't render the state it still changes the data on the state which you can see by refreshing, but here, I have made an entirely new array newLocation and have populated it with new data but it does not store the data to locations at all while destructuring the array inside setLocations works.
I do not understand what makes this happen. Can someone please provide me with a response.
Thank you and the code example is below.
const searchGeoLocation = async (event) => {
event.preventDefault();
const fetchedData = await fetch(url);
const data = await fetchedData.json();
const newLocation = [];
// This works without the for each
// newLocation.push(...data);
// setLocations(newLocation);
data.forEach(element => {
newLocation.push(element)
});
// Has the right array
console.log(newLocation);
// does not work and prints an empty array
setLocations(newLocation);
console.log(locations);
// Does Work
setLocations(...newLocation);
console.log(locations);
}
I understand why this behavior happens with the comments I got, and I am going to answer my question myself just so that people who stumble upon the same issue in the future can understand as well.
It seems changes on the state are only reflected when a re-render happens. The console.log I put in the function shows the state before the re-render takes place, so when I put the console.log function in the body, the changes are being reflected in the state.
I want to wait to apply state updates from the back-end if a certain animation is currently running. This animation could run multiple times depending on the game scenario. I'm using react-native with hooks and firestore.
My plan was to make an array that would store objects of the incoming snapshot and the function which would use that data to update the state. When the animation ended it would set that the animation was running to false and remove the first item of the array. I'd also write a useEffect, which would remove the first item from the array if the length of the array had changed.
I was going to implement this function by checking whether this animation is running or whether there's an item in the array of future updates when the latest snapshot arrives. If that condition was true I'd add the snapshot and the update function to my array, otherwise I'd apply the state update immediately. I need to access that piece of state in all 3 of my firestore listeners.
However, in onSnapshot if I try to access my state it'll give me the initial state from when the function rendered. The one exception is I can access the state if I use the function to set the state, in this case setPlayerIsBetting and access the previous state through the function passed in as a callback to setPlayerIsBetting.
I can think of a few possible solutions, but all of them feel hacky besides the first one, which I'm having trouble implementing.
Would I get the future state updates if I modify the useEffect for the snapshots to not just run when the component is mounted? I briefly tried this, but it seems to be breaking the snapshots. Would anyone know how to implement this?
access the state through calling setPlayerIsBetting in all 3 listeners and just set setPlayerIsBetting to the previous state 99% of the time when its not supposed to be updated. Would it even re-render if nothing is actually changed? Could this cause any other problems?
Throughout the component lifecycle add snapshots and the update functions to the queue instead of just when the animation is running. This might not be optimal for performance right? I wouldn't have needed to worry about it for my initial plan to make a few state updates after an animation runs since i needed to take time to wait for the animation anyway.
I could add the state I need everywhere on the back-end so it would come in with the snapshot.
Some sort of method that removes and then adds the listeners. This feels like a bad idea.
Could redux or some sort of state management tool solve this problem? It would be a lot of work to implement it for this one issue, but maybe my apps at the point where it'd be useful anyway?
Here's my relevant code:
const Game = ({ route }) => {
const [playerIsBetting, setPlayerIsBetting] = useState({
isBetting: false,
display: false,
step: Infinity,
minimumValue: -1000000,
maximumValue: -5000,
});
const [updatesAfterAnimations, setUpdatesAfterAnimations] = useState([]);
// updatesAfterAnimations is currently always empty because I can't access the updated playerIsBetting state easily
const chipsAnimationRunningOrItemsInQueue = (snapshot, updateFunction) => {
console.log(
"in chipsAnimationRunningOrItemsInQueue playerIsBetting is: ",
playerIsBetting
); // always logs the initial state since its called from the snapshots.
// So it doesn't know when runChipsAnimation is added to the state and becomes true.
// So playerIsBetting.runChipsAnimation is undefined
const addToQueue =
playerIsBetting.runChipsAnimation || updatesAfterAnimations.length;
if (addToQueue) {
setUpdatesAfterAnimations((prevState) => {
const nextState = cloneDeep(prevState);
nextState.push({ snapshot, updateFunction });
return nextState;
});
console.log("chipsAnimationRunningOrItemsInQueue returns true!");
return true;
}
console.log("chipsAnimationRunningOrItemsInQueue returns false!");
return false;
};
// listener 1
useEffect(() => {
const db = firebase.firestore();
const tableId = route.params.tableId;
const unsubscribeFromPlayerCards = db
.collection("tables")
.doc(tableId)
.collection("players")
.doc(player.uniqueId)
.collection("playerCards")
.doc(player.uniqueId)
.onSnapshot(
function (cardsSnapshot) {
if (!chipsAnimationRunningOrItemsInQueue(cardsSnapshot, updatePlayerCards)) {
updatePlayerCards(cardsSnapshot);
}
},
function (err) {
// console.log('error is: ', err);
}
);
return unsubscribeFromPlayerCards;
}, []);
};
// listener 2
useEffect(() => {
const tableId = route.params.tableId;
const db = firebase.firestore();
const unsubscribeFromPlayers = db
.collection("tables")
.doc(tableId)
.collection("players")
.onSnapshot(
function (playersSnapshot) {
console.log("in playerSnapshot playerIsBetting is: ", playerIsBetting); // also logs the initial state
console.log("in playerSnapshot playerIsBetting.runChipsAnimation is: "playerIsBetting.runChipsAnimation); // logs undefined
if (!chipsAnimationRunningOrItemsInQueue(playersSnapshot, updatePlayers)) {
updatePlayers(playersSnapshot);
}
},
(err) => {
console.log("error is: ", err);
}
);
return unsubscribeFromPlayers;
}, []);
// listener 3
useEffect(() => {
const db = firebase.firestore();
const tableId = route.params.tableId;
// console.log('tableId is: ', tableId);
const unsubscribeFromTable = db
.collection("tables")
.doc(tableId)
.onSnapshot(
(tableSnapshot) => {
if (!chipsAnimationRunningOrItemsInQueue(tableSnapshot, updateTable)) {
updateTable(tableSnapshot);
}
},
(err) => {
throw new err();
}
);
return unsubscribeFromTable;
}, []);
I ended up not going with any of the solutions I proposed.
I realized that I could access the up to date state by using a ref. How to do it is explained here: (https://medium.com/geographit/accessing-react-state-in-event-listeners-with-usestate-and-useref-hooks-8cceee73c559) And this is the relevant code sample from that post: (https://codesandbox.io/s/event-handler-use-ref-4hvxt?from-embed)
Solution #1 could've worked, but it would be difficult because I'd have to work around the cleanup function running when the animation state changes. (Why is the cleanup function from `useEffect` called on every render?)
I could work around this by having the cleanup function not call the function to unsubscribe from the listener and store the unsubscribe functions in state and put them all in a useEffect after the component mounts with a 2nd parameter that confirmed all 3 unsubscribe functions had been added to state.
But if a user went offline before those functions were in state I think there could be memory leaks.
I would go with solution #1: In the UseEffect() hooks you could put a boolean flag in so the snapshot listener is only set once per hook. Then put the animation state property in the useEffect dependency array so that each useEffect hook is triggered when the animation state changes and you can then run whatever logic you want from that condition.
Sorry for the kind of vague title. The best way to explain my question might be an example.
I have a of items in redux, and the list is displayed in a react component using standard react-redux connected components. Each individual item has a button, which when clicked, does some asynchronous work, and then removes the item from the list and puts it in another list displayed somewhere else. It's important that the logic for starting the asynchronous work be handled in redux because it's important to the state of my application.
That basic functionality works, but now I want to add feedback to the button so that when the side effect succeeds, it changes the label to a Checkmark (for simplicity, i'll do nothing and leave the list unchanged if the request fails in this example). The item will stick around for an extra second with the checkmark before being removed from the list.
The problem is that if i remove the item from the list as soon as the async work is done, it is immediately unmounted, so I need to delay that. I've been trying to come up with a way to implement this logic that is reusable across my app, as I'll want the checkmark feedback in other unrelated parts of the app.
The simple solution is to dispatch an action on success that just changes the state to indicate that the item's request succeeded, and then do a setTimeout to dispatch another action 1 second later to actually remove the item from the list.
I feel like doing that logic will become very repetitive if i do it in different places across my app where I have a button. I'd like to be able to not have to repeat the timeout logic for every new button that needs this. But I want what my app displays to represent the current state of my app.
Has anyone dealt with an issue like this before?
Thanks
Edit: I don't think it should really change the general solution, but I'm using redux-loop to handle side effects. I feel like a generic solution will work fine with thunk or saga or whatever else though.
You mentioned that you are using redux-loop to handle your async stuff. I'm more familiar with redux-thunk, so if it's ok with you, I'll give you an answer that uses a thunk.
You can keep your code DRY if you put the timeout in your action creator, and then call that action creator from multiple buttons:
// actionCreators.js
const fetchTheThings = (url, successAction, failureAction, followUpAction) => (dispatch) => {
//if you put the app in an intermediate state
//while you wait for async, then do that here
dispatch({ type: 'GETTING_THINGS' });
//go do the async thing
fetch(url)
.then(res => {
if (res.status === 200) return res.json();
return Promise.reject(res);
})
.then(data => {
//on success, dispatch an action, the type of which
//you passed in as an argument:
dispatch({ type: successAction, data });
//then set your timeout and dispatch your follow-up action 1s later
setTimeout(() => {
dispatch({ type: followUpAction });
}, 1000);
})
.catch(err => {
//...and handle error cases
dispatch({ type: failureAction, data: err });
});
};
//then you can have exported action creators that your various buttons call
//which specify the action types that get passed into fetchTheThings()
export const actionFiredWhenButtonOneIsPressed = () => {
return fetchTheThings('<some url>', '<success action>', '<failure action>', '<follow-up action>');
};
export const actionFiredWhenButtonTwoIsPressed = () => {
return fetchTheThings('<other url>', '<other success action>', '<other failure action>', '<other follow-up action>');
};
Hopefully that at least gives you some ideas. Good luck!
Ian's solution should be generalizable pretty well, but maybe, if you can live with a success confirmation that doesn't require DOM activity:
A simple unmount style that turns the element green and then fades it out, would be sufficient for a satisfying user feedback to tell that stuff has worked out.
I have this class:
export default class Search extends Component {
throttle(fn, threshhold, scope) {
var last,
deferTimer;
return function () {
var context = scope || this;
var now = +new Date,
args = arguments;
if (last && now < last + threshhold) {
// hold on to it
clearTimeout(deferTimer);
deferTimer = setTimeout(function () {
last = now;
fn.apply(context, args);
}, threshhold);
} else {
last = now;
fn.apply(context, args);
}
}
}
render() {
return (
<div>
<input type='text' ref='input' onChange={this.throttle(this.handleSearch,3000,this)} />
</div>
)
}
handleSearch(e) {
let text = this.refs.input.value;
this.someFunc();
//this.props.onSearch(text)
}
someFunc() {
console.log('hi')
}
}
All this code does it log out hi every 3 seconds - the throttle call wrapping the handleSearch method takes care of this
As soon as I uncomment this line:
this.props.onSearch(text)
the throttle methods stops having an effect and the console just logs out hi every time the key is hit without a pause and also the oSearch function is invoked.
This onSearch method is a prop method passed down from the main app:
<Search onSearch={ text => dispatch(search(text)) } />
the redux dispatch fires off a redux search action which looks like so:
export function searchPerformed(search) {
return {
type: SEARCH_PERFORMED
}
}
I have no idea why this is happening - I'm guessing it's something to do with redux because the issue occurs when handleSearch is calling onSearch, which in turn fires a redux dispatch in the parent component.
The problem is that the first time it executes, it goes to the else, which calls the dispatch function. The reducer probably immediately update some state, and causes a rerender; the re-render causes the input to be created again, with a new 'throttle closure' which again has null 'last' and 'deferTimer' -> going to the else every single time, hence updating immediately.
As Mike noted, just not updating the component can you get the right behavior, if the component doesn't need updating.
In my case, I had a component that needed to poll a server for updates every couple of seconds, until some state-derived prop changed value (e.g. 'pending' vs 'complete').
Every time the new data came in, the component re-rendered, and called the action creator again, and throttling the action creator didn't work.
I was able to solve simply by handing the relevant action creator to setInterval on component mount. Yes, it's a side effect happening on render, but it's easy to reason about, and the actual state changes still go through the dispatcher.
If you want to keep it pure, or your use case is more complicated, check out https://github.com/pirosikick/redux-throttle-actions.
Thanks to luanped who helped me realise the issue here. With that understood I was able to find a simple solution. The search component does not need to update as the input is an uncontrolled component. To stop the cyclical issue I was having I've used shouldComponentUpdate to prevent it from ever re-rendering:
constructor() {
super();
this.handleSearch = _.throttle(this.handleSearch,1000);
}
shouldComponentUpdate() {
return false;
}
I also moved the throttle in to the constructor so there can only ever be once instance of the throttle.
I think this is a good solution, however I am only just starting to learn react so if anyone can point out a problem with this approach it would be welcomed.
I'd like to call a component's function when network fetch completes.
function callRestApi({config, schema}) {
return axios(config).then((response) => {
if (schema) {
var data = normalize_json(response.data, schema)
response.entities = data.entities
}
return response
})
}
function* fetchEventList(action) {
try {
const response = yield call(callRestApi, action.payload);
// here I want to call a component's method if possible
yield put({type: action.response.action_type_success, response});
} catch (e) {
}
}
I can think of two ways to do this, and wonder if one is prefered over another or if there's a better way?
method1:
I include the component in the action payload so that I can call the method
method2:
on action.response.action_type_success, change redux state.
Then, component's componentWillReceiveProps compare if the state variable changed and calls the method
The second. You are using redux-saga to handle side effects, so keep it that way. You could add a callback to the action as method1 but I wouldn't mix concepts.
If you update the store on success, it will re-render the component and as you said you could check the newly updated prop in componentWillReceiveProps and trigger the function, however, check nextProps instead of this.props (but I bet you already know that).
This way everything flows one way, no callback hell :) + you can easily test the component just by passing a prop.
Although it's not a bad pattern per se, passing callbacks would be bi-directional flow, which breaks the first rule of flux: Unidirectional flow.