1

I have used react to create a website that retrieves data from a database, using REST API. On my home page, all data will be retrieved with useEffect and stored in a state. When the user searches in the form, it will match the data and send the user along with the found data to the corresponding page.

However, I would also like the user to directly get to the page by typing in the url. If a user bypasses the home page and goes directly to the specific page's url, then the searched page will not have the data(Assuming data was passed to the specific page from the home page, using props).

My temporary solution is to search the database every time a user switches between pages.

Is there a better solution such that the website has to only load in the data once?

Summary:

I would like to

  1. Let user search from home page using textfield
  2. Let user directly type in url to specific page (ex: websiteName/notes/myfirstnote)
  3. Prevent retrieval of data from database for every visited page (for efficiency purposes)

Home page code:

const Home = () => {
  const navigate = useNavigate()
  const [searchedNote, setSearchedNote] = useState('')
  const [allNotes, setAllNotes] = useState([])

  useEffect(() => {
    console.log("Home Page")
    fetch('databaseURL')
    .then(response => response.json())
    .then(data => setAllNotes(data.Items))
    .catch((error) => {
      console.error(error)
    })
  }, [])

  const searchNote = (event) => {
    //Omitting code to find the searched note
    navigate(`/notes/${foundNote.name}`)
  }

  //Rest of the code returns HTML code for Home
  //This includes the textfield to find a specific 'note'
  //The onsubmit function of the textfield is 'searchNote' which is stated above
}
export default Home

Notes page code:

const Notes = () => {
  const [allNotes, setAllNotes] = useState([])
  const [note, setNote] = useState()

  useEffect(() => {
    console.log("Welcome Notes")

    //Must get all data from database again. I would like to avoid doing this.
    fetch('databaseUrl')
    .then(response => response.json())
    .then(data => setAllNotes(data.Items))
    .catch((error) => {
      console.error(error)
    })
  }, [])

  //After getting database, filter out the 'note' of interest using the url
  //(ex: if url is websiteName/notes/myfirstnote, then search allNotes for name == 'myfirstnote'

  //Do things with the found note here

  //Rest of the code returns HTML code for Notes
}
export default Notes
yyy
  • 11
  • 2
  • Can you send the data to the Notes page, and if the notes page loads with no data present, it then hits the database? This answer may help: https://stackoverflow.com/a/52238733/3709812 –  Sep 21 '22 at 15:38

0 Answers0