React useParams returns 'string | undefined'
09:57 11 Mar 2023

I've seen this question asked elsewhere but none of the answers helped me. I'm using a parameter in the url and I'm wanting to access it with the useParam hook to then query my backend.

The destructured param is typed as 'string | undefined' - Is there a way to definitely type the destructured query param? I'd like to avoid having undefined values. I'm aware that I can just handle the undefined value in the functions that are expecting the param but I would just rather remove the issue at source, if possible.

Other answers suggested matching the destructured param value to the param name stipulated in the route component, but mine already match. Is it perhaps something to do with the nested routes under '/journalEntries', i.e. because other routes -without params- are possible on the 'journalEntries' route? I tried to figure this out by deleting the other child routes but it didn't help.

Routing:

const Routing = () => {
  return (
    
      
      <>
        
          } />
          } />

          
            
                  
                
              }
            />

=========================================================
     ROUTE I WANT TO DESTRUCTURE THE 'id' PARAMETER FROM:

            
                  
                
              }
            />
=========================================================

            
                  
                
              }
            />
          
        
      
    
  );
};
export default Routing;

Component containing link to single 'Journal Entry':

const JournalContainer = () => {
  const { journalEntries } = useDataContext();

  return (
    <>
      
{journalEntries.map((journalEntry) => { return (
====================================================================== LINK TO JOURNAL ENTRY ====================================================================== {journalEntry.title} {new Date(journalEntry.createdAt).toDateString()}
); })} Create a Journal Entry
); }; export default JournalContainer;

'Journal Entry' component which relies on the destructured parameter:

  const { id } = useParams(); // is typed as 'string | undefined'

  const methods = useForm({
    defaultValues: async () => await getJournalEntryById(id), // this function expects a string
  });
  const navigate = useNavigate();

  const [saveCopy, setSaveCopy] = useState(false);
  const [readOnly, setReadOnly] = useState(true);

  const submissionHandler: SubmitHandler = async (
    data
  ) => {
    await updateJournalEntryById(id, data); // this function expects a string
    if (saveCopy) {
      writeJournalEntryToFile(data);
    }
    navigate('/journalEntries');
  };

  return (
    
      
setSaveCopy(!saveCopy)} />
); }; export default JournalEntry;
  • made sure the param names matched
  • tried rendering a single route
typescript url react-hooks parameters react-router