javascriptreactjsswr

React - SWR - no update component


I know i'm going to feel very stupid but here goes. I have been learning React for a couple of weeks now (coming from all native javascript client side) and I have been fetching data using useEffect. But i'm seeing more and more remarks to avoid this and use SWR instead. But the component does not show the received data. I know this is going to be something simple but after multiple hours searching i'm giving up and asking the question: What prevents this component from updating on recieving data?

const MissieDetail = () => {

const { data: missions, isLoading, error } =
    useSWR('GetMissions', GetMissions, {
        onSuccess(data, key, config) {
            console.log(data)
        }
    })
let content
if (isLoading) { content = <p>Loading...</p> }
if (error) { content = <p>{error.message}</p> }
content =
    <ul>
        {
            missions.map((mission) => {
                <li key={mission.id}>{mission.titel}</li>
            })
        }
    </ul>
return (
    <main>
        <h2>Mission List</h2>
        {content}
    </main>
)}

I am receiving data. At that moment the "loading" message disappears but no li are added to the ul enter image description here


Solution

  • Nothing is being returned from the .map iterator function - it has curly brackets, which means it's a function body. Either remove the curly brackets to make it a single-line function with implicit return or add a return statement:

    // classic `return` statement
    content =
      <ul>
        {
          missions.map((mission) => {
            return <li key={mission.id}>{mission.titel}</li>;
          })
        }
      </ul>
    
    // OR single-line arrow function, implicit return
    content =
      <ul>
        {
          missions.map((mission) =>
            <li key={mission.id}>{mission.titel}</li>
          )
        }
      </ul>