How to update component from non-React environment? - javascript

I have most of my html code generated by server, but some things are much faster and easier to do in client with React so I need to create Component not in #root, but somewhere deep inside of my page. The nature of my application is that after the page is loaded it needs to retrieve data via API and it does it 5-6 times in a row with some small pause between each of requests. This normally takes from 10 to 30 seconds.
On the first request I can just check if element is not rendered yet and render it normally:
if('sorter' in window === false) {
window.sorter = preactRender(<Sorter filterBoundaries={window.filters} />, document.querySelector('.sorter-holder'))
}
But then I need to send new props to <Sorter /> in order to update it with newly arrived data. But how could I do it? I tried to do window.sorter.forceUpdate(), but it doesn't work because React's render method returns Element, which obviously doesn't have method forceUpdate().
Maybe it would be a lot easier to remove old component and render it anew from the scratch? Even if it's anti-patern.

I just sorted it out simply. I added to my application a global variable indicating if sorter needs and update:
if('sorter' in window === false) {
window.sorter = preactRender(<Sorter filterBoundaries={window.filters} />, document.querySelector('.sorter-holder'))
} else {
window.sorterUpdatePending = true
}
Then in my component I created an interval to check whether sorter update is pending or not. When it is - force an update and reset global variable. And when search is finished it clears the interval.
componentDidMount() {
var checkInterval = setInterval(() => {
if(window.sorterUpdatePending === true) {
this.forceUpdate()
window.sorterUpdatePending = false
}
if(window.isSearching === false) {
clearInterval(checkInterval)
}
}, 100)
}

Related

How can I get my state to wait on API data before it fires off?

I have a paginator that determines how many pages to present, based off a data prop that is JSON array's of data from an API.
const itemsPerPage = 3;
const [noOfPages] = React.useState(
Math.ceil(data[0]?.length / itemsPerPage)
);
My issue is, how can I create some sort of conditional to wait for the noOfPages state to fire off before receiving the data prop?
Without ?., I'm getting an undefined issue.
{ data && console.log(data[0].length)} This works just fine, when testing if there is actually data inside the prop. I am not able to re-create this same sort of conditional for my state to wait for the data prop before firing off.
React always renders current state of your application. This means that all state variables exist as long as component that said values attached to exist. Your goal is to orchestrate said state to render what you want to render - that is called "state management".
You can go with different solutions here. For example, you can avoid rendering component until data is loaded, or replace that component with some sort of indication. Or you can set your state to some initial value, like 0 and render null until it will become some positive number. This will not work if it is possible that your value will be 0, but this can be mitigated with another state value. Consider this example:
function Pagination() {
// Here we have one of two possible distinct states: "loading" and "not_loading"
// It is good to use strings for such states, since later you might want to introduce new state, like "error"
let [loading_state, set_loading_state] = useState("loading");
// This is number of pages. It should always exist, but until we are in "not_loading" state we don't actualy care what it would be
let [number_of_pages, set_number_of_pages] = useState(0);
useEffect(function () {
// retrieve data
let data = ...;
// set number of pages and loading state
set_number_of_pages(data[0].length / items_per_page);
set_loading_state("not_loading");
}, []);
if (loading_state === "loading") return null;
if (loading_state === "not_loading") return ....;
}
There would be modifications, depending on where you keep and how you retrieve your data. Sometimes it is even better to calculate values "on the fly", instead of keeping them in state. If there would be some performance heavy computation, you can always use useMemo hook, but this is not your case.

Call function only after multiple states have completed updating

Logic:
I have a dialog for converting units. It has two stages of choice for the user: units to convert from and units to convert to. I keep this stage as a state, dialogStage, for maintainability as I'm likely going to need to reference what stage the dialog is in for more features in the future. Right now it's being used to determine what action to take based on what unit is clicked.
I also have a state, dialogUnits, that causes the component to rerender when it's updated. It's an array of JSX elements and it's updated via either foundUnitsArray or convertToUnitsArray, depending on what stage the dialog is at. Currently both states, dialogStage and dialogUnits, are updated at the same moment the problem occurs.
Problem:
When choosing the convertTo units, displayConversionTo() was still being called, as though dialogStage was still set to 'initial' rather than 'concertTo'. Some debugging led to confusion as to why the if (dialogStage == 'initial') was true when I'd set the state to 'convertTo'.
I believe that my problem was that the dialogStage state wasn't updated in time when handleUnitClick() was called as it's asynchronous. So I set up a new useEffect that's only called when dialogStage is updated.
The problem now is that the dialog shows no 'convertTo' units after the initial selection. I believe it's now because dialogUnits hasn't updated in time? I've swapped my original problem from one state not being ready to another state not being ready.
Question
How do I wait until both states are updated before continuing to call a function here (e.g. handleUnitClick()?).
Or have I mistaken what the problem is?
I'm new to react and, so far, I'm only familiar with the practice of state updates automatically rerendering a component when ready, unless overridden. Updating dialogUnits was displaying new units in the dialog until I tried to update it only when dialogStage was ready. It feels like an either/or situation right now (in terms of waiting for states to be updated) and it's quite possible I've overlooked something more obvious, as it doesn't seem to fit to be listening for state updates when so much of ReactJs is built around that already being catered for with rerenders, etc.
Component code:
function DialogConvert(props) {
const units = props.pageUnits;
const [dialogUnits, setDialogUnits] = useState([]);
const [dialogStage, setDialogStage] = useState('initial');
let foundUnitsArray = [];
let convertToUnitsArray = [];
units.unitsFound.forEach(element => {
foundUnitsArray.push(<DialogGroupChoice homogName={element} pcbOnClick={handleUnitClick} />);
});
useEffect(() => {
setDialogUnits(foundUnitsArray);
}, []);
useEffect(() => {
if (dialogStage == "convertTo") {
setDialogUnits(convertToUnitsArray);
}
}, [dialogStage]);
function handleClickClose(event) {
setDialogStage('initial');
props.callbackFunction("none");
}
function handleUnitClick(homogName) {
if (dialogStage == "initial") {
// getConversionChoices is an external function that returns an array. This returns fine and as expected
const choices = getConversionChoices(homogName);
displayConversionTo(choices);
} else if (dialogStage == "convertTo") {
// Can't get this far
// Will call a function not displayed here once it works
}
}
function displayConversionTo(choices) {
let canConvertTo = choices[0]["canconvertto"];
if (canConvertTo.length > 0) {
canConvertTo.forEach(element => {
convertToUnitsArray.push(<DialogGroupChoice homogName={element} pcbOnClick={handleUnitClick} />);
});
setDialogStage('convertTo');
}
}
return (
<React.Fragment>
<div className="dialog dialog__convertunits" style={divStyle}>
<h2 className="dialogheader">Convert Which unit?</h2>
<div className='js-dialogspace-convertunits'>
<ul className="list list__convertunits">
{dialogUnits}
</ul>
</div>
<button className='button button__under js-close-dialog' onClick={handleClickClose}>Close</button>
</div>
</React.Fragment>
)
}
So, there are some issues with your implementations:
Using non-state variables to update the state in your useEffect:
Explanation:
In displayConversionTo when you run the loop to push elements in convertToUnitsArray, and then set the state dialogStage to convertTo, you should be facing the issue that the updated values are not being rendered, as the change in state triggers a re-render and the convertToUnitsArray is reset to an empty array because of the line:
let convertToUnitsArray = [];
thus when your useEffect runs that is supposed to update the
dialogUnits to convertToUnitsArray, it should actually set the dialogueUnits to an empty array, thus in any case the updated units should not be visible on click of the initial units list.
useEffect(() => {
if (dialogStage == "convertTo") {
// as your convertToUnitsArray is an empty array
// your dialogue units should be set to an empty array.
setDialogUnits(convertToUnitsArray)
}
}, [dalogStage]);
You are trying to store an array of react components in the state which is not advisable:
http://web.archive.org/web/20150419023006/http://facebook.github.io/react/docs/interactivity-and-dynamic-uis.html#what-components-should-have-state
Also, refer https://stackoverflow.com/a/53976730/10844020
Solution: What you can do is try to save your data in a state, and then render the components using that state,
I have created a code sandbox example how this should look for your application.
I have also made some changes for this example to work correctly.
In your code , since you are passing units as props from parent, can you also pass the foundUnitsArray calculated from parent itself.
setDialogUnits(props.foundUnitsArray);
and remove the below operation,
units.unitsFound.forEach(element => {
foundUnitsArray.push(<DialogGroupChoice homogName={element} pcbOnClick={handleUnitClick} />);
});

React instance value or State for minor UI update

In my mind, whenever I call setState of React Component I believe at least a little work is done to refresh the Component. To store every important dynamic variable in the state is a niche I have seen so far in the community.
Imagine this none trivial code that sets searching variable to true when a server request is yet to return.
fetchSearch = async (food) => {
this.searching = true;
const request = await client.get(`http://localhost:8081/food?q=${food}`);
const results = await request.json();
this.setState((state) => {
this.searching = false;
return { searchResult: results }
});
}
<Input showSpinner={this.searching}</Input>
As you may have guessed the value of this.searching is a determinant of if the Loading UI animation CSS class is applied.
My question is if it is really worth setting this.searching in the state with the extra WORK of refreshing the Component, as opposed to using an instance value ? What are the possible troubles I can run into ? What benefit do I derive other than having a central store for instance ?
Since you are already updating the state for searchResult, updating another field searching will not cause additional rerenders.
If your UI relies on searching you will need to have it in the state, otherwise react would not know that searching value has changed.
React is already very performant, there is no need to overthink before you actually encounter any issues with the performance.

React state gets "corrupted"

I am working on a simple React.JS frontend piece.
I essentially have a browsing SPA for historical data. The design has a bunch of filters that I need to populate one at a time, starting the top one in my logic hierarchy.
I do something like:
componentWillMount() {
if (!this.props.advertisers) {
this.props.loadAdvertisers();
}
}
Once advertisers array has been loaded, I map it to options of a select component (using react-select), set the selection to the first item in the list and load the next list - campaigns.
As far as I understand, the best way to do this is still componentWillReceiveProps() and I am a little perplexed how this should be done differently, given that componentWillReceiveProps is being phased out.
My code looks like:
componentWillReceiveProps(nextProps) {
if (nextProps.advertisers && !this.props.advertisers) {
const advertiser = nextProps.advertisers[0];
this.setState({
advertiser: {
value: advertiser['id'],
label: advertiser['name']
}
});
nextProps.loadCampaigns(advertiser['id']);
}
// if campaigns list changed, reload the next filtered array
if (nextProps.campaigns && this.props.campaigns !== nextProps.campaigns) {
...
}
This worked fine, until I decided to add a loading indicator. I mapped state's loading property e.g. for campaigns it gets exposed via this.props.campaignsLoading then do:
return (this.props.campaignsLoading || this.props...Loading || ...) ?
<ProgressIndicator> : <MainContentPanel>
The problem is now, my state does not get set correctly inside componentWillReceiveProps().
The project is using #rematch and I initially tried this with #rematch/loading plugin and when the problem happened, thought the plugin does it wrong, somehow. Then, I mapped loading properties manually, and just added two more dispatches to manually set the loading flag.
All the props are being set/unset correctly, but my state is not being set and nothing works. Any suggestions?
When you do
if (nextProps.advertisers && !this.props.advertisers) {
You are not comparing the next and the previous props. "this.props.advertisers" is probably already set so you never go into the setState line. Although using componentWillReceiveProps is no longer the recommended way to go (You Probably Don't Need Derived State), what you probably want to do roughly is:
if (nextProps.advertisers && nextProps.advertisers !== !this.props.advertisers) {

ReactJS: How to handle component state when it's based on AJAX?

Summary: New to ReactJS and I'm trying to figure out the best way to update a component when it's state depends on a remote API (i.e. keep component state in sync with remote database via AJAX API).
Example Use Case: Think of a product inventory where clicking a button adds a product to your cart and decrements the inventory by 1. Every time the user clicks it initiates an AJAX request and then upon completion of the request, the component re-renders with the new product inventory by calling setState().
Problem: I've ran into an issue where because both setState() and the AJAX request are asynchronous, the component becomes out of the sync with the server. For example if you click really quickly you can initiate more than one AJAX request for a single product ID because the component's state has not yet updated to reflect that the product ID is no longer in inventory. I have a simple example below to illustrate the concept:
Inadequate Solution: This could be handled on the server side by sending an error back if the client request a product that is no longer in inventory, however I'm really looking for the best way to handle this common scenario in ReactJS on the client side and to make sure I'm understanding the best way to handle component state.
Component extends React.Component {
constructor(props) {
super(props);
this.state = {
clicksLeft: 0,
};
}
componentDidMount() {
//getClicksLeft is async and takes a callback, think axios/superagent
getClicksLeft((response) => {
this.setState(response);
});
}
btnClicked = () => {
//This may appear redundant/useless but
//imagine sending an element in a list and then requesting the updated
//list back
const data = {clicks: this.state.clicksLeft--};
decrementClicksLeft(data, () => {
getClicksLeft((response) => {
this.setState(response);
});
}
}
render() {
<button onClick={this.btnClicked}>Click me {this.state.clicksLeft} times</button>
}
}
Is there any reason to have to call getClicksLeft when the button is clicked? You have already called it when the component is mounted and then anytime the button is clicked you just decrement that number by one.
btnClicked = () => {
if (this.state.clicksLeft > 0) {
decrementClicksLeft();
this.setState({clicksLeft: this.state.clicksLeft - 1});
}
}
This would work if there is only one user trying to buy stuff at a time. Otherwise you could also check the amount left before making the purchase.
btnClicked = () => {
getClicksLeft((response) => {
if (response > 0) {
decrementClicksLeft();
this.setState({clicksLeft: this.state.clicksLeft - 1});
}
});
}
This way if there are no clicks left, nothing happens.
The most basic solution would be to disable the button while you wait for the response to come back:
(I've also made your code simpler.)
Component extends React.Component {
constructor(props) {
super(props);
// Initial state
this.state = {
clicksLeft: 0, // No clicks are availabe
makeRequest: false, // We are not asking to make a request to the server
pendingTransaction: false, // There is no current request out to the server
};
}
componentDidMount() {
// Initial load completed, so go get the number of clicks
this._getClicksRemaining();
}
// Called whenever props/state change
// NOT called for the initial render
componentWillUpdate(nextProps, nextState) {
// If there is no existing request out to the server, AND if the next
// state is asking us to make a request (as set in _handleButtonClick)
// then go make the request
if (!this.state.pendingTransaction && nextState.makeRequest) {
const data = {
clicks: this.state.clicksLeft--,
};
// decrementClicksLeft is async
decrementClicksLeft(data, () => this._getClicksRemaining());
// First fire off the async decrementClicksLeft request above, then
// tell the component that there is a pending request out, and that it
// is not allowed to try and make new requests
// NOTE this is the one part of the code that is vulnerable to your
// initial problem, where in theory a user could click the button
// again before this setState completes. However, if your user is able
// to do that, then they are probably using a script and you shouldn't
// worry about them. setState/render is very fast, so this should be
// more than enough protection against human clicking
this.setState({
makeRequest: false,
pendingTransaction: true,
});
}
}
_getClicksRemaining() {
// getClicksLeft is async
getClicksLeft((response) => {
// Here we are inside of the callback from getClicksLeft, so we
// know that it has completed. So, reset our flags to show that
// there is no request still pending
const newState = Object.assign(
{
pendingTransaction: false,
},
response,
);
this.setState(newState);
});
}
// The button was clicked
_handleButtonClick = () => {
if (!this.state.pendingTransaction) {
// If there isn't a request out to the server currently, it's safe to
// make a new one. Setting state here will cause `componentWillUpdate`
// to get called
this.setState({
makeRequest: true,
});
}
}
render() {
// Disable the button if:
// * there are no clicks left
// * there is a pending request out to the server
const buttonDisabled = ((this.state.clicksLeft === 0) || this.state.pendingTransaction);
return (
<button
disabled={buttonDisabled}
onClick={this._handleButtonClick}
>
Click me {this.state.clicksLeft} times
</button>
);
}
}
After spending some time with react-redux, redux-thunk and redux-pack I decided to go with something simpler: react-refetch. I didn't really need the complexities of redux as I am only doing post and get operations on lists. I also need some simple side effects like when I do a post, I need to update multiple lists (which is achieved through andThen() in react-refetch).
This solution has much less boiler plate and works great for small projects. The core reason to choose this project over react-redux can be summarized in this quote from heroku's blog entry:
Looking around for alternatives, Redux was the Flux-like library du jour, and it did seem very promising. We loved how the React Redux bindings used pure functions to select state from the store and higher-order functions to inject and bind that state and actions into otherwise stateless components. We started to move down the path of standardizing on Redux, but there was something that felt wrong about loading and reducing data into the global store only to select it back out again. This pattern makes a lot of sense when an application is actually maintaining client-side state that needs to be shared between components or cached in the browser, but when components are just loading data from a server and rendering it, it can be overkill.
1: https://github.com/heroku/react-refetch
2: https://engineering.heroku.com/blogs/2015-12-16-react-refetch/

Categories