How to update component based on container's state change

Multi tool use
Multi tool use
The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP


How to update component based on container's state change



I have a React container called UserContainer which renders a component called UserComponent.


UserContainer


UserComponent



The code looks approximately like this (I have removed the unnecessary bits):


// **** CONTAINER **** //
class UserContainer extends React.Component<ContainerProps, ContainerState> {
state = { firstName: "placeholder" };

async componentDidMount() {
const response = await this.props.callUserApi();

if (response.ok) {
const content: ContainerState = await response.json();
this.setState({ firstName: content.firstName });
}
}

private isChanged(componentState: ComponentState) {
return this.state.firstName === componentState.firstName;
}

async save(newValues: ComponentState) {
if (!this.isChanged(newValues)) {
console.log("No changes detected.");
return;
}

const response = await this.props.changeFirstName(newValues.firstName);

if (response.ok) {
const content: ContainerState = await response.json();
this.setState({ firstName: content.firstName });
}
}

render() {
return <UserComponent firstName={this.state.firstName} onSave={(newValues: ComponentState) => this.save(newValues)} />;
}
}

export default UserContainer;

// **** COMPONENT **** //

class UserComponent extends React.PureComponent<ComponentProps, ComponentState> {
constructor(props: ComponentProps) {
super(props);

this.state = { firstName: props.firstName }
}

render() {
return (
<div>
<input type="text" value={this.state.firstName} onChange={evt => this.setState({ firstName: evt.target.value})} />
<button type="button" onClick={() => this.props.onSave(this.state)}>Save</button>
</div>
);
}
}

export default UserComponent;



The problem is that this.state.firstName in the component is always "placeholder". Even after the container gets its values from the API, the state of the component is not changed (however, the props are changed). When adding console.log into the individual methods, the flow of individual steps is following:


this.state.firstName


state


props


console.log



As you can see, the component constructor is called just once, prior to the container receiving its data from the backend API. Is there a way to pass the updated container state into the component in order to display the real data?









By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

25Vz qui69v6lPXiUopcJkYAa8VLb5A
SF45w3NZ 9wDZrCo165KHPhsQbme ZdSdv7CLzTx,CE8MJ,VFn6fO AS4A3,l hhH4 V

Popular posts from this blog

Makefile test if variable is not empty

Visual Studio Code: How to configure includePath for better IntelliSense results

Will Oldham