Access useState hook in Action #10264
-
Hello all, I have a page that sends a post request to an api, and the api body must include an array of integers. The array is stored using react's useState hook inside of the same component. The api is called in a react-router action on form submit. How can I include this array in my api call? It isn't part of the form so it isn't passed to the action inherently. Should I keep this array as a value in a hidden form element? This seems cumbersome and would require converting to strings and then back to integers I think. Is there a better way to pass my array to the action so I can include it in the API call? Should I avoid using an action in this case and just call a function inside the component body so I can access the useState hook? Neither of those solutions seems very clean so I'm afraid I'm missing something in the way react-router handles things. Any advice on the best way to proceed would be appreciated, thanks!! |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
I ended up getting some advice in the Discord server. In case anyone else stumbles upon this question, the best method is to use JSON.serialize to hold the array in a hidden form element.
Then in the action use JSON.parse to get the array back and include in the api call.
|
Beta Was this translation helpful? Give feedback.
I ended up getting some advice in the Discord server. In case anyone else stumbles upon this question, the best method is to use JSON.serialize to hold the array in a hidden form element.
<Form><input name="data" type="hidden" value={JSON.stringify(state)} /></Form>
Then in the action use JSON.parse to get the array back and include in the api call.
export async function action({ request, params }) { const body = Object.fromEntries(await request.formData()); body.data = JSON.parse(body.data); return callAPI(body); }