Home > OS >  I get error while trying to read text from file in reactjs/tauri
I get error while trying to read text from file in reactjs/tauri

Time:11-27

im building crypto wallet in reactjs and then i will make it in tauri but what im tryng to do now is to read mnemonic from text file but i get this error img

the code is this:

    fetch(raw)
    .then(r => r.text())
    .then(text => {
      console.log(text); // console logs output


    });

    

  const [computer] = useState(
    new Computer({
      mnemonic: (text), // i want here to be output but i get that error

CodePudding user response:

There are a couple problems here. The initial problem, and the reason the error occurred, is because the text variable is out of scope when you are calling it inside the useState hook. You will need to set the state value when you have reference to the text variable.

The second problem is that you are wanting to set the initial value of the a state in a react component based off an asynchronous query. Since an asynchronous value cannot be available at the initial render, you need to combine the useState hook and the useEffect hook to set the value after the initial load.

With such limited code shown, i will try to fill in the gaps and make an example of what i think you are looking for:

function Component() {
  const [computer, setComputer] = useState("");
  
  useEffect(() => {
    fetch(raw).then(r => r.text()).then(text => {
      setComputer(new Computer({ mnemonic: text }))
    })
  }, [])

  return (
    // whatever you render 
  )
}

This way, at render your component will have a default value of "" and then when the async fetch call has finished it will update the value. If you pass an empty array as the second parameter to the useEffect hook, it will only be called on the initial render.

  • Related