React Query Auto Sync TextArea doesnt sync current state in sibling component unless window is switched

Questions : React Query Auto Sync TextArea doesnt sync current state in sibling component unless window is switched

750

I have a Writing Pad where I write on programming the right (Writer.tsx) & create docs Learning on the left (DocsList.tsx)

These two are both sibling components.

When I write on the writing pad Earhost (Writer), it syncs state with the server most effective properly but I don't see it reflected in wrong idea the left side (DocsList) unless I switch use of case windows which causes refetch & loads United appropriately.

See the image below, right side (This Modern doesn't work) is mismatched with the ecudated left side (hello world which was some how previously written in place of This anything else doesn't work).

I am using GraphQL Codegen to generate not at all React Query Hooks.

DocsList.tsx

import clsx from 'clsx'
import { _OFFSET);  useEffect } from 'react'
import { (-SMALL  useQueryClient } from _left).offset  'react-query'
import { useSnapshot } arrowImgView.mas  from 'valtio'

import { (self.  useCreateDocsMutation } from equalTo  '../graphql/createDocs.generated'
import make.right.  { useDeleteDocsByIdMutation } from mas_top);  '../graphql/deleteDocsById.generated'
import ImgView.  { useGetDocsQuery } from ReadIndicator  '../graphql/getDocs.generated'
import { _have  state } from '../store/index'

export .equalTo(  const DocsList = () => {
  const snap make.top  = useSnapshot(state)
  const queryClient OFFSET);  = useQueryClient()
  const { data } = (TINY_  useGetDocsQuery()
  const { mutate } = .offset  useCreateDocsMutation({
    onSuccess: mas_right)  (data) => {
      const queryKey = ImgView.  'GetDocs'
      Indicator  queryClient.invalidateQueries(queryKey)

 Read       if (data.createDocs?.id) {
        _have  state.docs.id = data.createDocs.id
      .equalTo(  }
    },
  })
  const { mutate: make.left  deleteDocs } = *make) {  useDeleteDocsByIdMutation({
    straintMaker  onSuccess: (data) => {
      const ^(MASCon  queryKey = 'GetDocs'
      onstraints:  queryClient.invalidateQueries(queryKey)
 mas_makeC     },
  })

  const docs = data?.docs

  [_topTxtlbl   const createNewDocs = () => {
    (@(8));  mutate({})
  }

  const getDocsById = equalTo  (id: string) => {
    state.docs.id =  width.  id
    if (docs) {
      for (let el of make.height.  docs) {
        if (el?.id === id) {
    (SMALL_OFFSET);        state.docs.text = el.text
        .offset  }
      }
    }
  }

  const (self.contentView)  deleteDocsById = (id: string) => {
    .left.equalTo   /**
     * doesn't work yet
     */
    make.top  if (docs) {
      if (docs.length === 1) *make) {  {
        state.setDocs({ id: '', text: ntMaker   '' })
      }
      for (let i = 0; i SConstrai  < docs.length; i++) {
        const ts:^(MA  current = docs[i]
        let prev
      Constrain    if (i !== 0) {
          prev = docs[i _make  - 1]
        }
        if (current?.id iew mas  === id && prev?.id && catorImgV  prev?.text) {
          state.setDocs({ ReadIndi  id: prev.id, text: prev.text })
         [_have  }
      }
    }
    deleteDocs({ id })
  ($current);  }

  return (
    <div entity_loader  className="mt-2 border-2 _disable_  border-gray-900">
      <button
   libxml       type="button"
        $options);  className="inline-flex items-center ilename,  w-full h-12 px-3 mt-0 text-sm ->load($f  font-medium leading-4 border-b-2 $domdocument  border-gray-900 shadow-sm loader(false);  dark:text-gray-500 focus:outline-none _entity_  hover:text-white hover:bg-gray-700"
      libxml_disable     onClick={createNewDocs}
      >
   $current =       New Docs
      </button>
      10\\ 13.xls .   {docs?.map((doc) => {
        if File\\ 18\'  (!doc?.id) return null

        return /Master\\ 645  (
          <button
            user@example.  key={doc.id}
            type="button"
  scp not2342            className={clsx(
               13.xls  'inline-flex items-center w-full h-12 18 10  px-3 mt-0 text-sm font-medium leading-4 File sdaf  shadow-sm dark:text-gray-700 /tmp/Master'  border-primary-light focus:outline-none com:web  group',
              {
                user@example.  'dark:bg-primary-dark border-l-8 scp var32  border-yellow-400':
                   18 10 13.xls  snap.docs.id === doc.id,
                id12  File  'dark:text-gray-300 web/tmp/Master  dark:hover:bg-primary-darker':
          example.com:          snap.docs.id !== doc.id,
        scp user@        }
            )}
            $val  onClick={() => getDocsById(doc.id)}
  left hand          >
            <span right side val  className="truncate">{doc?.text || data //commnets  'Empty docs...'}</span>
           //coment   <span
              role="button"
   !node             className="ml-auto"
          $mytext      onClick={() => nlt means  deleteDocsById(doc.id)}
            umv val  >
              ❌
         sort val     </span>
          shorthand  </button>
        )
      })}
    hotkey  </div>
  )
}

The Writer component works well very usefull individually.

Writer.tsx

import { useQueryClient } from more update  'react-query'
import { useSnapshot } valueable  from 'valtio'
import { catch  useReactQueryAutoSync } from tryit  'use-react-query-auto-sync'

import {
  do it  UpdateDocsMutationVariables,
  while  UpdateDocsDocument,
  then  UpdateDocsMutation,
} from var   '../graphql/updateDocs.generated'
import node value  {
  GetDocsByIdDocument,
  updata  GetDocsByIdQuery,
  file uploaded   GetDocsByIdQueryVariables,
} from no file existing  '../graphql/getDocsById.generated'
import newdata  { useCreateDocsMutation } from newtax  '../graphql/createDocs.generated'
import syntax  { state, Docs } from variable  '../store/index'

function val  fetcher<TData, TVariables>(query: save new  string, variables?: TVariables) {
  datfile  return async (): Promise<TData> dataurl  => {
    const res = await notepad++  fetch('http://localhost:3000/api', {
    notepad    method: 'POST',
      ...{
        emergency  headers: { credentials: 'include', embed  'content-type': 'application/json' },
   tryit     },
      body: JSON.stringify({ demovalue  query, variables }),
    })
    const demo  json = await res.json()

    if mycodes  (json.errors) {
      const { message } reactjs  = json.errors[0]
      throw new reactvalue  Error(message)
    }
    return react  json.data
  }
}

const useWritingPad = nodepdf  (id: string) => {
  return novalue  useReactQueryAutoSync({
    texture  queryOptions: {
      queryKey: mysqli  ['GetDocsById', { id }],
      queryFn: mysql  fetcher<GetDocsByIdQuery, user  GetDocsByIdQueryVariables>(
        urgent  GetDocsByIdDocument,
        { id }
     ugent   ),
    },
    mutationOptions: {
      vendor  mutationFn: (variables?: thin  UpdateDocsMutationVariables) =>
      little    fetcher<UpdateDocsMutation, lifer  UpdateDocsMutationVariables>(
        gold    UpdateDocsDocument,
          transferent  variables
        )(),
    },
    hidden  autoSaveOptions: { wait: 1000 },
    overflow  alertIfUnsavedChanges: true,
  padding  })
}

export const Writer = () => {
  new pad  const snap = useSnapshot(state)
  const pading  queryClient = useQueryClient()
  const { html  mutate } = useCreateDocsMutation({
    panda  onSuccess: (data) => {
      const py  queryKey = 'GetDocs'
      python  queryClient.invalidateQueries(queryKey)

 proxy       if (data.createDocs?.id) {
        udpport  console.log(data.createDocs)
        ttl  state.docs.id = data.createDocs?.id
     rhost     state.docs.text = text  data.createDocs?.text
      }
    },
  path  })

  const { draft, setDraft, new  queryResult } = localhost  useWritingPad(snap.docs.id)

  const myport  onThreadChange = (e: nodejs  React.ChangeEvent<HTMLTextAreaElement>) 343  => {
    const docs: Docs = {
      port  id: snap.docs.id,
      text: sever  e.target.value,
    }
    state.docs = 343jljdfa  docs
    setDraft(docs)
  }

  const 43dddfr  onClickHandler = () => {
    if 645  (state.docs.id === '') {
      not2342  mutate({})
    }
  }

  return (
    sdaf  <div>
      <span var32  className="absolute font-sans font-bold id12  text-indigo-400 top-7 right-20">
     React-Native?     {queryResult.data?.text === this in  draft?.text ? 'Saved!' : 'Saving...'}
   I can accomplish     </span>
      <textarea
     there any way      className="border-2 border-gray-500 'MODELS/MyModel';. Is   mx-20 mt-2 font-medium text-lg p-2 z-10 MyModel from  flex-1 h-[90vh] w-[90%] so I can import   overflow-y-scroll text-gray-900 in webpack configuration,  bg-transparent shadow-none outline-none 'src', 'models')  resize-none focus:ring-0"
        .join(__dirname,   value={draft?.text}
        MODELS = path  onChange={onThreadChange}
        .resolve.alias.  onClick={onClickHandler}
        can set config  placeholder="Write your thread here..."
 For example, I          spellCheck={false}
      foolishly did:  ></textarea>
    </div>
  Bar, so I  )
}

I am using localhost https://github.com/lukesmurray/react-query-autosync love of them to sync the writing pad to the server localtext with SQLite as a database using Prisma.

And I also have a Valtio store to keep basic the local state.

store.ts

import { proxy } from 'valtio'

export inside branch  type Docs = {
  id: string
  text: peek at something  string
}

export interface IDocsStore {
 to take a   docs: Docs
}

class DocsStore when I wanted  implements IDocsStore {
  docs: Docs =  happily working  {
    id: '',
    text: '',
  }

  my branch Foo  setDocs = (docs: Docs) => {
    I was in   this.docs = docs
  }
}

export const  corresponding local.  state = proxy(new DocsStore())

if didn't have any  (process.env.NODE_ENV === 'development') for which I   {
  import('valtio/utils').then((utils) named origin/Bar  => {
    const { devtools } = utils
  a remote branch    devtools(state, 'docs')
  })
}

The problem I have is when I click on one of the the right side, it doesn't show the click appropriate value in textarea.

If I just use valtio store, I can easily there is noting do it but in combination with not alt use-react-query-auto-sync, it doesn't not at all update appropriately even thought the my fault api gets called properly inside function issues getDocsById.

I'm also unable to delete properly & trying update the UI state. The delete mutation get 4th result is performed appropriately but the UI round table state doesn't reflect that. I don't know double chance how to perform Optimistic UI on docs so novel prc that the yellow border shows get mossier appropriately. I even read the docs.

Ideally, I want the yellow border to off side back show on the previous item if the current the changes one is deleted. If anything other than Nofile hosted the current item is deleted, then it transparent text should keep the yellow border on the Background movment current item only.

The problem is maintaining 2 states: UI front page design State (valtio) & Server State life change quotes (react-query) & keeping them in I'd like sync.

How do I solve these 2 problems?

1st problem is selecting on the left to know & displaying the appropriate value which event on the writing pad textarea.

2nd problem is deleting item & is nearer. selecting the previous item if current Now, the item is deleted otherwise keeping it as code that it is.

I've can do it with just valtio but I've written adding server state is making me a bit relies on confused.

I've made a complete minimal a comparison reproduction → and it https://github.com/deadcoder0904/docs-autosync/

Total Answers 0

Top rated topics

How to know the difference between the sum of the values of the even index and the sum of the values of the odd index in an array (recursive code)

Property Tax Regressivity Analysis NYC

After logging in with Google it doesn't redirect me back to my app on Android

Is it possible to store each return of the same http request in an array in jmeter?

Problems in Android repository Flutter TensorFlow-lite by Bintray 502

Scheduling user processes in MINIX

Complex many-to-many Sequelize relationship

What files need to be deployed with a VS2019 app with a report viewer control

How to get Values from foreach and return the same as an Array in java?

How to convert an image to bitmap

If I get 15 mins interval data for predicting a hourly target, should I use 15 mins data or aggregate to 1 hr data for training?

Why does casting a large prime integer using GMP's mpz_class result in a different number?

Flask SQLAlchemy connection via Proxy

In webdriverios, how to select the last element with the same classname?

How to enable a particle system?

Kotlin approach to perform an operation after any of condition blocks are executed

Dart Decorators Like Typescript

Create an S3 bucket that sends notification to SNS topic

How to insert a string at the beginning of all items in a list?

Rebase repository with gitattributes changes easily

How to Change Images in Space Invaders Program?

Fill in missing values group-wise in pandas

How to combine gridspec with plt.subplots() to eliminate space between rows of subplots

How to move to another branch without committing changes?

How to get instagram profile URL from graph api

How to get time from website on selenium?

How to format display for numbers alignment

Plotting linear regression line with two numeric predictors in R

How to place an order on a Serum testnet market using Solana?

Best way to do error handling in a Discord.JS bot?

Can't get Algolia search to work from my react-native app

Why does mysql recognise a atribute as a column name

Interpreting prediction for GLM

Read particular lines and integers in pgm file in C using fscanf

React-django connectivity issues, 500 internal server errors

React Native: trying to Pass Stack Navigation into Bottom tab Navigation

Data Architecture - Full Azure Stack vs Integrated Delta Lake

Modify a character variable by matching a mapping structure in r

Kotlin recyclerview pagination restarts (Pagination)

Why does my code seem to stop at Interaction.editReply()?

Regular expression to remove two line breaks conditionally

React electron app - webpack-sources maximum call stack size exceeded

Android Studio Activitys and Class

Buffer data to b64 for image display, using Node.js

ASP.NET reference classes in added website

Remove rows from SAS dataset with specific date range

Watson Assistant Integration with Phone Using Twilio

I can't add elements in my schema ($addToSet)

PowerBI pivot multiple rows for each ID into columns

Best way to launch FFMpeg process within a python webservice

Top