Skip to content

Commit

Permalink
handle undefined data properly, fixes #138
Browse files Browse the repository at this point in the history
  • Loading branch information
IdoPesok committed Jun 22, 2024
1 parent 0ba650d commit 388c36b
Show file tree
Hide file tree
Showing 4 changed files with 23 additions and 5 deletions.
5 changes: 5 additions & 0 deletions .changeset/bright-apples-breathe.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"zsa-react": patch
---

Fix isSuccess with undefined data
3 changes: 3 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -35,3 +35,6 @@ jobs:

- name: Test
run: npm run test

- name: Typecheck
run: npm run typecheck
9 changes: 8 additions & 1 deletion packages/zsa-react/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -142,7 +142,12 @@ export const useServerAction = <
if (oldResult.status === "filled") {
setResult(oldResult.result)
} else {
setResult({ error: err, isError: true, data: undefined })
setResult({
error: err,
isError: true,
data: undefined,
isSuccess: false,
})
}

// clear the old data
Expand All @@ -162,6 +167,7 @@ export const useServerAction = <
isError: false,
error: undefined,
data: data ?? undefined,
isSuccess: true,
}

setResult(res)
Expand Down Expand Up @@ -234,6 +240,7 @@ export const useServerAction = <
isError: false,
error: undefined,
data: data ?? undefined,
isSuccess: true,
})
},
[execute]
Expand Down
11 changes: 7 additions & 4 deletions packages/zsa-react/src/results.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import {
*/
export type TInnerResult<TServerAction extends TAnyZodSafeFunctionHandler> = {
isError: boolean
isSuccess: boolean
error: undefined | inferServerActionError<TServerAction>
data: undefined | inferServerActionReturnData<TServerAction>
}
Expand Down Expand Up @@ -101,22 +102,22 @@ export const calculateResultFromState = <
isSuccess: false,
status: "pending",
}
} else if (isPending && oldResult.status === "filled" && result.data) {
} else if (isPending && oldResult.status === "filled" && result.isSuccess) {
return {
isPending: true,
isOptimistic: true,
data: result.data,
data: result.data as any,
isError: false,
error: undefined,
isSuccess: false,
status: "pending",
}
} else if (!result.isError && result.data) {
} else if (result.isSuccess) {
// success state
return {
isPending: false,
isOptimistic: false,
data: result.data,
data: result.data as any,
isError: false,
error: undefined,
isSuccess: true,
Expand Down Expand Up @@ -156,12 +157,14 @@ export const getEmptyResult = <
? // if there is no initial data
{
isError: false,
isSuccess: false,
error: undefined,
data: undefined,
}
: {
// if there is initial data
isError: false,
isSuccess: true,
error: undefined,
data: initialData,
}
Expand Down

0 comments on commit 388c36b

Please sign in to comment.