I am trying to develop a react chat app UI like WhatsApp. It's a one-page app. All the components are functional components and I am using hooks to handle the local state. I am using React Router to handle sidebar routes, redux to add dummy data to contacts state
Problem:
When I click on the contact name in the contact list, the sidebar component loads and it works fine even though the URL changes.
But when I try to refresh at the same URL. I get an undefined error. I got some hint that when I refresh the page on another URL like http://localhost:3000/users/3 , the error is because of the reason that the component loads first, and since it's accessing data from the state even though the contact state is empty.
Below is the data I m rendering in the app component
Index file
<React.StrictMode>
<Router>
<Provider store={store}>
<App />
</Provider>
</Router>
</React.StrictMode>,
App component
<>
<Container fluid style={styles.app}>
<Row>
<Col style={styles.leftSidebar} className="leftSidebar">
<Row>
<Row>
<h2 style={{ color: 'white' }}>Profile Component</h2>
</Row>
<Row style={{ margin: 'auto' }}>
<SearchBar searchChange={onSearchChange} />
</Row>
</Row>
<Row style={styles.contactList}>
<ContactList contacts={filteredContacts} />
</Row>
</Col>
<Col>
<Switch>
<Route
path="/conversations/:id"
render={(props) => (
<ConversationList
{...props}
contacts={contacts}
setContacts={setContacts}
/>
)}
/>
<Route component={NoConvo} />
</Switch>
</Col>
</Row>
</Container>
</>
I have tried many different approaches but none seems to work. I just want that when i refresh on another route, the data gets loaded first then the component uses the data which will handle the undefined error