Next.js Discord

Discord Forum

useOptimistic works with server actions but not fetch requests...

Unanswered
Cape lion posted this in #help-forum
Open in Discord
Cape lionOP
Hello all, I have this function which uses useOptimistic to update the UI prior to a mutation using a server action. I found that the server actions are being processed sequentially rather than in parallel despite my awaiting Promises.allSettled. So I turned to making simple API fetch requests. That solved the problem and now they are processed in parallel.

However, upon invoking the function the UI is immediately updated but then reverts to the initial state prior to the fetch requests completing. This removes the optimistic update from the UI (which disappears).

Any thoughts on resolving this?

  const [optimisticData, mutate] = useOptimistic(images, optimisticListUpdate)

  const handlePut = async () => {

    startTransition(() => {
      for(let k=0; k<files.length; k++) {
        mutate({
          type: 'add',
          body: {
            id: Math.random().toString(36),
            file: files[k],
          }
        })
      }
    })

    const pn = []
    for(let k=0; k<files.length; k++) {
      let formData = new FormData()
      formData.append('agent_id', agent.id)
      formData.append('file', files[k])

      // Option 1: Server Action
      // const p = uploadAgentImage(null, formData)

      // Option 2; Fetch API Request
      const p = fetch(`/api/agents/${agent.id}/images`, {
        method: 'POST',
        body: formData,
      })

      pn.push(p)
    }

    const res = await Promise.allSettled(pn)

    const isAllSuccess = res.every(r => r.status==='fulfilled')
    if(isAllSuccess) {
      revalidate({ tag: 'images_agent'})
    }

  }

0 Replies