{"id":16299188,"url":"https://github.com/nejcrogelsek/react-query-tutorial","last_synced_at":"2025-04-09T19:48:47.948Z","repository":{"id":39058360,"uuid":"497600110","full_name":"nejcrogelsek/react-query-tutorial","owner":"nejcrogelsek","description":"Learn how to use react query. Tutorial videos are made by Codevolution.","archived":false,"fork":false,"pushed_at":"2022-06-01T19:00:19.000Z","size":268,"stargazers_count":1,"open_issues_count":0,"forks_count":0,"subscribers_count":1,"default_branch":"master","last_synced_at":"2025-02-15T11:49:24.384Z","etag":null,"topics":["react-query","react-query-devtools","typescript"],"latest_commit_sha":null,"homepage":"https://www.youtube.com/watch?v=Ev60HKYFM0s\u0026list=PLC3y8-rFHvwjTELCrPrcZlo6blLBUspd2\u0026index=4","language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nejcrogelsek.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2022-05-29T13:33:00.000Z","updated_at":"2022-06-14T17:08:20.000Z","dependencies_parsed_at":"2022-09-18T22:23:56.961Z","dependency_job_id":null,"html_url":"https://github.com/nejcrogelsek/react-query-tutorial","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nejcrogelsek%2Freact-query-tutorial","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nejcrogelsek%2Freact-query-tutorial/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nejcrogelsek%2Freact-query-tutorial/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nejcrogelsek%2Freact-query-tutorial/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nejcrogelsek","download_url":"https://codeload.github.com/nejcrogelsek/react-query-tutorial/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":248103290,"owners_count":21048233,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["react-query","react-query-devtools","typescript"],"created_at":"2024-10-10T20:47:09.069Z","updated_at":"2025-04-09T19:48:47.909Z","avatar_url":"https://github.com/nejcrogelsek.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Query tutorial\n\nTutorial videos are made by [Codevolution](https://www.youtube.com/watch?v=Ev60HKYFM0s\u0026list=PLC3y8-rFHvwjTELCrPrcZlo6blLBUspd2\u0026index=3).\n\nCode is separated with different branches. Every video has his own branch.\n\n**First steps:**\n\n1. Clone project by running:\n   `git clone https://github.com/nejcrogelsek/react-project-template.git`\n2. Delete .git file inside cloned project.\n3. Run: `yarn run start:clean`\n4. Run: `yarn run husky:postinstall` to install husky git hook (automatically formats the code when pushing code to github)\n\n5. Before running the app you need to serve mock data with: `yarn run serve-json`. If you go to http://localhost:4000/superheroes you will see the data.\n\n## About react-query\n\nLink to [offical website](https://react-query.tanstack.com/).\n\n**1. react-query cache**\n\nThe first time useQuery is fired for superheros key, isLoading flag is set to true and network request is send to fetch the data. When the request is completed it is cached used the query key (superheroes) and the fetchSuperHeroes function as the unique identifiers.\n\nWhen we revisit the page react query will check if the data for this query exists in cache. If the data exists in the cache, the cached data is immediately returned without isLoading flag set to true.\n\nReact query knows that the server data might be updated and that the cache doesn't contain the latest data. So a background refetch is triggered for the same query and if the response is successful the displayed data is updated in the UI.\nAs our data in this example is the same as the cached data, we don't see any differences. But you can change the db.json file and see the changes for yourself.\n\nTo indicate the background refetch state, react-query provides us with the flag called isFetching.\n\nReact query cache the data so we don't need to see the loading indicator every time we visit the page.\n\nThe default cache time is set to 5 mintes. We can change it with options cacheTime property\n\n**2. react-query stale time**\n\nLet's say the data doesn't change that often. We can set the stale time to 30 seconds and the user will see the cached query results or cached data for 30 seconds before refetching it again. The default state time is set to 0 seconds.\n\n0 seconds is possibly the safest value you can set to stale time, which is also the default value.\n\n**3. react-query refetchOnMount**\n\nIf set to true, the query will refetch on mount if the data is stale. If set to false, will disable additional instances of a query to trigger background refetches. If set to 'always', the query will always refetch on mount. If set to a function, the function will be executed with the latest data and query to compute the value Defaults to true.\n\nDefault value is set to true.\n\n**4. react-query refetchOnWindowFocus**\n\nIf set to true, the query will refetch on window focus if the data is stale. If set to false, the query will not refetch on window focus. If set to 'always', the query will always refetch on window focus. If set to a function, the function will be executed with the latest data and query to compute the value. Defaults to true.\n\nDefault value is set to true.\n\n**5. react-query refetchInterval - Polling**\n\nFetching data at regular intervals. For example: If you have component that shows real time price of different stocks, you might want to fetch the data every second so is in sync with UI.\n\nFor that react-query provides us with `refetchInterval` flag.\n\nDefault value is set to false.\n\nPolling is paused when the window lose focus. To fix that issue we can set `refetchIntervalInBackground` property to true.\n\n**6. Homework (Solution on branch: feature/09-homework)**\n\nCombine polling with callbacks. Use the `refetchInterval` option to pull the api data every 3 seconds. Behind the scenes add a fourth superhero of your choice to the superheroes array in `db.json`.\n\n    a) Within the onSuccess callback check if the number of heroes is 4 and ifit is the case I want you to stop the polling.\n    b) Within the onError callback I want you to stop the polling.\n\nHint:\nMantain state variable whose initial value is 3000. State variable will be assigned to `refetchInterval` configuration. In callbacks check for the response / errors and set the state variable to false.\n\n**7. react-query select - Data Transformation**\n\nFor data tranformation react-query provides us with `select` flag.\n\n`select` is function that receives onSuccess response and transform out data in the way we want it.\n\nIn our example we transformed data to be an array of just heroes names instead of whole response.\n\n**8. QueryById - 2 solutions**\n\nWe can query by id in two ways (look commits under branch name: `feature/12-queryById`).\n\n    \ta) Solution 1 or first commit: **QueryById with manuali passed ID**\n    \t\t- We can manually pass id into fetch function: file `useSuperHeroData`\n    \tb) Solution 2 or second commit: **QueryById with react-query automatic passed id**\n    \t\t- React query automatically pass id into fetch function: file `useSuperHeroData`\n\n**9. react-query - Parallel queries**\n\nSometimes a single component needs to call multiple APIs to fetch the necessary data. With react-query with simply call useQuery twice.\n\n**10. react-query - Dependent queries**\n\nDependent query - is dependent on the results of another query.\n\n**11. react-query initialData - Initial query data**\n\nOn react-query heroes page we have displayed different heroes. If we click on the hero, we see `loading` text for a moment. To get rid of that initial loading statement, we can set `initialData` in useSuperHeroData.tsx file. If we refresh detail page, the loading button will show because we don't have any initial data at the start, because we skipped the fetch all super heroes query.\n\n**12. react-query keepPreviousData - Paginated queries**\n\nIf we add flag `keepPreviousData` into the useQuery options, when we paginate to next page, the data from the previous page is still displayed till the new data is successfully fetched.\n\n**13. react-query - Handling mutation response**\n\nHandling mutation response will save you additional network request.\n\n**14. react-query - Optimistic updates**\nUpdating the state before performing a mutation under the assumption that nothing can go wrong.\n\n`onMutate:` is called before the mutation function is fired and is passed the same variables that mutation function would receive.\na) Cancel any outgoing refetches so they don't override our optimistic update.\nb) Get a hold of the current query data before we make any update. This will help us role back in case the mutation fails.\n`onError:` is called if the mutation encounters an error.\n`onSettled:` is called if the mutation is either successfull or encounters an error. `invalidateQueries` will ensure client state is in sync with server state. The user will not notice a difference.\n\n## Available Scripts\n\nIn the project directory, you can run:\n\n### `yarn start:clean`\n\nRemove `node_modules` \u0026 `yarn.lock` \u0026 `yarn-error.log` files.\nThen it runs: `yarn` to install all packages \u0026 finally `yarn start` to run the app in the development mode.\\\n\nOpen [http://localhost:3000](http://localhost:3000) to view it in the browser.\n\nThe page will reload if you make edits.\\\nYou will also see any lint errors in the console.\n\n### `yarn start`\n\nRuns the app in the development mode.\\\nOpen [http://localhost:3000](http://localhost:3000) to view it in the browser.\n\nThe page will reload if you make edits.\\\nYou will also see any lint errors in the console.\n\n### `yarn test`\n\nLaunches the test runner in the interactive watch mode.\\\nSee the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.\n\n### `yarn build`\n\nBuilds the app for production to the `build` folder.\\\nIt correctly bundles React in production mode and optimizes the build for the best performance.\n\nThe build is minified and the filenames include the hashes.\\\nYour app is ready to be deployed!\n\nSee the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.\n\n### `yarn eject`\n\n**Note: this is a one-way operation. Once you `eject`, you can’t go back!**\n\nIf you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.\n\nInstead, it will copy all the configuration files and the transitive dependencies (webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.\n\nYou don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.\n\n### `yarn generate:page PageName`\n\nGenerates new page with specified name.\n\n### `yarn generate:component ComponentName`\n\nGenerates new component with specified name.\n\n### Check for updates\n\n- `yarn update:check` - Check for any packages updates.\n- `yarn update:single packageName` - Updates one package.\n- `yarn update` - Updates all packages.\n\n### Prettier\n\n- `yarn code:check` - Check for any prettier errors.\n- `yarn code:format` - Format code.\n- `yarn code:format:specific-file` - Format specific file.\n\n### eslint\n\n- `yarn lint` - Check for any eslint errors.\n- `yarn lint:fix` - Fix some of the errors.\n\n## Learn More\n\nYou can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).\n\nTo learn React, check out the [React documentation](https://reactjs.org/).\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnejcrogelsek%2Freact-query-tutorial","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnejcrogelsek%2Freact-query-tutorial","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnejcrogelsek%2Freact-query-tutorial/lists"}