0

Hello I need replace word in string with react state variable and hold the reference: example:

Const [mystate, setMyState] = useState({user:"miuser",html:""});

let htmlString = getHtmlStringFromApi(); // get "<p>{{username}}</p>"

//I try

setMyState(...mystate, html: htmlString.replace("{{username}}", mystate.user));

return(

<div dangerouslySetInnerHTML={{__html: mystate.html}}></div>

)

The problem is that the state html var changes; My div doesnt change. Any idea to replace with state by reference? Thanks

  • Is this the actual code ? If not can you please post the actual code you are using. I can see some syntax errors in the code you have posted. – PR7 Apr 13 '22 at 02:00
  • Hello , is the part of code that I have a trouble, sorry the code is too big but this is the main idea ; I can't replace this Word with state by reference – Jose Ahías Vargas Apr 13 '22 at 02:06
  • In above code you are not setting the state correctly. You are not passing object to `setMyState()`. It should be like this: `setMyState({ ...mystate, html: htmlString.replace("{{username}}", mystate.user) });` – PR7 Apr 13 '22 at 02:13
  • Also `getHtmlStringFromApi()` looks like an asynchronous API call which returns a `Promise` so you will need to use `await` or `then()` to wait for the API data and then set your state. – PR7 Apr 13 '22 at 02:17
  • You can refer to this post for how to make API calls : https://stackoverflow.com/questions/38742334/what-is-right-way-to-do-api-call-in-react-js – PR7 Apr 13 '22 at 02:20
  • Hello sorry for the example; yes this method need await but this code is like a pseudo code; the point is that the replace doesnt set the reference of the state in the string; because only set the text; I need set the reference ; thanks – Jose Ahías Vargas Apr 13 '22 at 03:09

1 Answers1

0

As per my understanding, you can use the useEffect() hook with dependency array to reflect the changes of state in the html string. So whenever the htmlString is updated, your state will also get updated with new html.

const [htmlString, setHtmlString] = useState("");
const [mystate, setMyState] = useState({user:"miuser",html:""});

useEffect(() => {
    const getData = async () => {
      const res = await getHtmlStringFromApi(); // get "<p>{{username}}</p>"
      setHtmlString(res);
    };
  
    getData();
}, []);

// This will update the html in mystate whenever htmlString is updated
useEffect(() => {
    setMyState({ ...mystate, html: htmlString.replace("{{username}}", mystate.user) });
}, [htmlString]);

return (
    <div dangerouslySetInnerHTML={{__html: mystate.html}}></div>
)
PR7
  • 1,524
  • 1
  • 13
  • 24