Reputation: 139
I know that setState is asynchronous. I can’t decide which solution would be more elegant in my case. The problem is that 1 component is on hook and another is on classes.
I tried wrapping it in a callback, and tried didUpdate, but it didn’t work for me. Props str always remains for 1 render in MyOldCLassComponent . I understand that when the function starts its action str == '' because has not received the value yet, its value depends on isSearch == true.
The main problem. After the state inside the function becomes true, this is trigated in the hook component to a request to my api , and the api value is placed in the str variable. But since the function has already been called in another component, its str was different at the time of the call, it remains the same, how best to avoid this.I want str to be updated dynamically inside the start function, but it is asynchronous
What can be done so as not to change the logic too much?
export default class ParentComp extends Component {
constructor(props) {
super(props);
this.state = {
isSearch: false,
str: ''
};
updateIsSearc = (status) => {
this.setState({ isSearch: status });
};
updateStr = (newString) => {
this.setState({ strWithApostrophe: newString});
};
renderhtml = () => {
const { isSearchWithApostrophe, strWithApostrophe } = this.state;
return ( <>
<HookTSXComponent
str= {this.str}
updateSearchResult={this.updateStr}
isSearchingWithSuffix={isSearch}
/>
<MyOldCLassComponent
str={this.str}
updateIsSearc={this.updateIsSearc}
</>
}
Since I have to use a certain hook, then in a new component with the hook I get the following logic
const HookTSXComponent: React.FC<EnhancedSearchProps> = ({
str,
isSearchingWithSuffix,
updateSearchResult,
}) => {
const { handleSearch, apiAnswer } = useEnhancedSearchHandling({
queryParameters: str},
});
useEffect(() => {
if (isSearchingWithSuffix) {
validateAndSearchQuery(
searchResult,
isSearchingWithSuffix,
handleSearch,
);
}
}, [isSearchingWithSuffix]);
const formattedSearchResult = useMemo(() => {
if (isSearchingWithSuffix && previewData && !Array.isArray(previewData)) {
return typeof previewData === 'string'
? previewData.trim()
: JSON.stringify(previewData);
}
}, [previewData]);
useEffect(() => {
if (
formattedSearchResult &&
formattedSearchResult !== searchResult &&
isSearchingWithSuffix
) {
updateSearchResult(formattedSearchResult);
}
}, [formattedSearchResult]);
return <></>;
};
export default React.memo(HookTSXComponent);
Second old comp
class MyOldCLassComponent extends Component {
start= () => {
if (1 === 1) {
this.props.updateIsSearc(true);
}
const answer = this.props.str
consle.log('updated str', answer)
}
render() {
return (
<button onClick={this.start}>Click</button>
);
}
}
Upvotes: 0
Views: 46