[WP] 28.02.2023 | AJAX

 

fig 1.1 ajax requests scheme 

-----------------------------------------------------------------------

This day was especially hard step in my journey.Amount of time spent on a single exercise involving network communications using http protocol and ajax(older XMLHttpRequest or more recent fetch() interface) and basic display of received information shows how much I have ahead of me to learn. Anyway I am going to roll my sleeves up and continue in my strive!


All surroundings were described. The exercise was mainly about fetching data and conditionaly render it on a screen. Peace of cake u say. It may be… but to be honest I had some probles in getting the requested outcome. I was given pre made index page and API response specifics. The endpoint was given. User input in search bar was to be passed to API via query params with GET request URL. Final url passed to fetch had form of `${ENDPOINT}?searchTerm=${searchTerm}`. I used fetch method as await expression within async function and assigned it to response variable. Furthermore I assigned parsed response to json variable.


In this case handling of the request needed to be supported by aditional piece of state – additional status state variable have been created.The initial status variable value was set to „idle”. After checking if response status was ok (!json.ok) if there were any members of results field of the response the status was set to „success” and if result array was empty status was set to „empty”. If the response was neither successfull nor empty it was marked as „error” – located in else block. There was one additional „loading” status and it was set right after getRequest function call was made- the first instruction of a function body. In the return statement information paragraphs were conditionally rendered(condition&&<p>msg</p>) for loading, empty and error status cases. for success case json.result array of objects was mapped and for each result <SearchResult result={result} key=result.isbn/> component was rendered. isbn field of result object was used as key argument for mapping.


Async function was handling the reuest was wired up to the form via onSubmit attribute of <form> tag. The very first instruction of the function body was event.preventDefault() as by default submited form require another html page to be loaded after submit event(html document is specified in action argument of <form> tag). There was possible improvement to the code structure and organization. It assumed to pass search result piece of state to a whole new component and fill it with mapping logic.


The most difficult part of the exericise was to come up with idea to abstract the request state into separate state variable and present separate conditionally rendered or mapped elements in case of each state.


Ready for more

gmarcin

Komentarze

Popularne posty z tego bloga

[WP] 23.06.2023 | subjects

15.07.2024 | simplicity

[WP] 05.06.2023 | angular-intro