Giter Club home page Giter Club logo

Comments (4)

rametta avatar rametta commented on May 27, 2024

Yes that is exactly how mutations work, you are not expected to have the information right away, you pass the dynamic data to the myMutation.mutate(payload) function.

For rapini, you take the mutations from the intiialize, so

const { mutations } = initialize(axios)

// inside component
const myMutation = mutations.useMyMutation()
const onFormSubmit = () => {
  myMutation.mutate({ my dynamic data goes here })
}

hope that helps. The react query mutation docs has more details on that

from rapini.

cn-johndpope avatar cn-johndpope commented on May 27, 2024

that's helpful - thank you
but still not clear how to do the straightforward - checking of errors - and if it is an error - show message.

some historic boilerplate code I've used in the past - where ICredential is username / password

async function loginUserClearCookies(credentials: ICredential) {

        console.error("WARNING - deleting existing session details if any...")
        const keys = ['tokenExpiredCount', 'token', 'user'];
        await AsyncStorage.multiRemove(keys);

        const hasInternet = checkConnectivity();
        if (!hasInternet) {
            setErrorMessage('No internet detected...');
            SnackbarHandler.errorToast("No internet...");
            return
        }
        setPreload(true);
        SnackbarHandler.normalToast("Authorising...");

/// HERE I CAN CALL MUTATE - but am I expecting this inside a try / catch ? and then handling error? 
        NocApi.post('/logon', credentials)
            .then(response => {
                if (response.data) {
                    setErrorMessage('');
                    const token = `wa=wsignin1.0&wresult=${encodeURIComponent(
                        response.data
                    )}`;
                    // console.log('token', token);
                    if (token) {
                        Promise.all([
                            setUser(credentials),
                            postTokenForCookie(token), // this will transition ui isAuthenticated -> true -> logged in > and kick off fetchAll once we get cookie
                            setToken(token),
                        ])
                            .then(async (res) => {
                                setPreload(false);
                            })
                            .catch(err => {
                                console.error('err', err);
                                Analytics.trackEvent(err.message);
                                SnackbarHandler.errorToast("🔥  LOGIN FAILED!!!");
                                setPreload(false);
                            });
                    }
                }
            })
            .catch(error => {
                setPreload(false);
                let err = error as AxiosError
                Analytics.trackEvent(err.message)
                if (err.message == "Network Error") {
                    console.error("We cancelled the request!!");
                    SnackbarHandler.errorToast(err.message);
                    return;
                }
                SnackbarHandler.errorToast('Email or Password not correct');
            });
    }

UPDATE

this is some boiler plate code that I'm wrapping around to the typescript librrary / axios spat out by swagger-codegen-cli-3.0.41.jar

java -Xmx1024m -jar swagger-codegen-cli-3.0.41.jar generate -i openapi.yaml -l typescript-axios -o generate --additional-properties npmName=@flow,npmVersion=0.0.59,private=false

  const handleLogin = async () => {
    setLoading(true);
    setError('');

    try {
      var model:UserLoginModel = {}
      model.userName = username
      model.password = password
      //usePostAuth(model);

      let result = UsersApiFp().postAuth(model);
      console.log("result:",result);
      setLoading(false);
    } catch (e) {
      setLoading(false);
      setError('Invalid username or password');
    }
  };

from rapini.

rametta avatar rametta commented on May 27, 2024

@cn-johndpope this seems like a general react query mutation question, there are a lot of docs about how to use it here https://tanstack.com/query/v4/docs/react/guides/mutations . You don't need separate states for loading or errors, don't need a try/catch either, it's all built-in to the hook

from rapini.

cn-johndpope avatar cn-johndpope commented on May 27, 2024

ok touche - this example is perfect. Would be better to replace the other one you have which falls short of showcasing finer details.
I can see a path forward now - thanks
I hit a snag using the tanstak v4 - I'll raise separate ticket.

function App() {
  const mutation = useMutation({
    mutationFn: (newTodo) => {
      return axios.post('/todos', newTodo)
    },
  })

  return (
    <div>
      {mutation.isLoading ? (
        'Adding todo...'
      ) : (
        <>
          {mutation.isError ? (
            <div>An error occurred: {mutation.error.message}</div>
          ) : null}

          {mutation.isSuccess ? <div>Todo added!</div> : null}

          <button
            onClick={() => {
              mutation.mutate({ id: new Date(), title: 'Do Laundry' })
            }}
          >
            Create Todo
          </button>
        </>
      )}
    </div>
  )
}

from rapini.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.