changing url from one to another in one second reactjs

Viewed 34

React beginner here, learning by coding, i have a project of mine where i have a small problem (this code is somehow near to my real code, cant share real code),

my question how can i have my newSnapshot for under a second to be this:

let newSnapshot =api/cam/${site.identifier}/+${allCams[0].identifier}/snapshot;

then after it automatically change to this:

let newSnapshot =api/cam/${site.identifier}/+${cam.identifier}/snapshot;

English is not my mother langugage so could be mistakes, any question just ask me.

  const [state, setState] = useState({
    snapshotUrl: "",
  });

   const updatePreview = () => {

  const allCams=[{identifier: '7-7-7'}]
  const site={identifier: '1-1-1'} 
  const cam={identifier: '0-0-0'} 
  
  let newSnapshot =
        `api/cam/${site.identifier}/` +
        `${cam.identifier}/snapshot`;

  setState({
          ...state,
            snapshotUrl: newSnapshot,
        });

}

1 Answers

You need a useEffect with setTimeout inside of it. Also if you are planning to run this useEffect with [allCams, site, cam] deps array - ensure those values are memoized in some way, with useState or with useMemo, due to you can get an infinite useEffect execution and infinite rerender.

const { useState } = React;

function App() {
  const [state, setState] = useState({
    snapshotUrl: ""
  });

  const updatePreview = () => {
    const allCams = [{ identifier: "7-7-7" }];
    const site = { identifier: "1-1-1" };
    const cam = { identifier: "0-0-0" };

    const snStart = `api/cam/${site.identifier}/${allCams[0].identifier}/snapshot`;
    const snAfter = `api/cam/${site.identifier}/${cam.identifier}/snapshot`;

    setState((currState) => ({ ...currState, snapshotUrl: snStart }));

    setTimeout(() => {
      setState((currState) => ({ ...currState, snapshotUrl: snAfter }));
    }, 1000);
  };

  return (
    <div className="App">
      <p>{state.snapshotUrl}</p>
      <button type="button" onClick={updatePreview}>
        Update
      </button>
    </div>
  );
}

ReactDOM.createRoot(
    document.getElementById("root")
).render(
    <App />
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.1.0/umd/react.development.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.1.0/umd/react-dom.development.js"></script>
<div id="root"></div>

Related