Code Monkey home page Code Monkey logo

formik-persist's Introduction

Formik Persist

Persist and rehydrate a Formik form.

npm install formik-persist --save

Basic Usage

Just import the <Persist > component and put it inside any Formik form. It renders null!

import React from 'react'
import { Formik, Field, Form } from 'formik'
import { Persist } from 'formik-persist'

export const Signup = () =>
  <div>
    <h1>My Cool Persisted Form</h1>
    <Formik
      onSubmit={values => console.log(values)}
      initialValues={{ firstName: '', lastName: '', email: '' }}
      render={props =>
        <Form className="whatever">
          <Field name="firstName" placeholder="First Name" />
          <Field name="lastName" placeholder="Last Name" />
          <Field name="email" type="email" placeholder="Email Address" />
          <button type="submit">Submit</button>
          <Persist name="signup-form" />
        </Form>}
    />
  </div>;

Props

Only three props!

  • name: string: LocalStorage key to save form state to
  • debounce:? number: Default is 300. Number of ms to debounce the function that saves form state.
  • isSessionStorage:? boolean: default is false . Send if you want Session storage inplace of Local storage

Author

Todo

  • Alternative storages (localForage)
  • Support AsyncStorage for React Native

formik-persist's People

Contributors

anujsachan1990 avatar jaredpalmer avatar krevels avatar mvanlonden avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

formik-persist's Issues

[question] Would it work with redux-persist?

We have a need to save the state of the form in case user leaves the page with form half completed. At moment we're planning to use Redux Form but I would like to try Formik (because, why not?), and we're using redux-persist to save our app state in localForage.

Anyone with experience mixing redux-persist with formik-persist? Does it even make sense?

Deleting localStorage entry

I'm using Persist in forms and I want them persisted while the user hasn't submitted the form. Once the user submits the form it should clean up. So what I did was onSubmit I use localStorage.removeItem("form-name");

That works and removes but just ms later it creates a new entry in localStorage again.

My specific state structure is a simple success boolean. If true it returns just a success component and if not renders the form.

What could be happening? I assumed that without any component rendering it wouldn't submit more entries to localStorage

Turn off persistence for specific fields

Is there any way to have persistence applied to a form but turn it off for a specific field? I have a file upload field handled by react-dropzone that persists just the path but not the actual reference to the file on reload.

hook api?

would make sense to transform this in a hook api?

invalid relative reference to formik

npm version 6.4.1, node version 8.11.3
[email protected]

npm i formik-persist

inspecting dist/formik-persist.d.ts shows

export declare const Persist: React.ComponentClass<PersistProps, React.ComponentState> & {
    WrappedComponent: React.ComponentClass<PersistProps & {
        formik: import("../../../../../../../Users/jared/workspace/github/jaredpalmer/formik-persist/node_modules/formik/dist/types").FormikContext<any>;
    }, React.ComponentState>;
};

and I see the following error:

TS2307: Cannot find module '../../../../../../../Users/jared/workspace/github/jaredpalmer/formik-persist/node_modules/formik/dist/types'.

How to use with useFormik hook?

When trying to use Formik using the useFormik, I understandably get the following warning:

Warning: Formik context is undefined, please verify you are rendering <Form>, <Field>, <FastField>, <FieldArray>, or your custom context-using component as a child of a <Formik> component. Component name: PersistImpl

And data is not persisting. What should I do?

Form state only saved once

I have this SPA that has a TabView (Primereact) where one tab sit s a Formik component, another eventually to display a DataTable, another with an iframe showing an app from another server, and then another tab for future content. At first, the form data would disappear when I changed tabs, but then I tried formik-persist and it works once. I can enter data on the form and then change tabs and come back and the data is still there. But, if I do nothing in the form and repeat the steps, the next time I come back to the form, everything has been reset. I tried looking at what you did in the persist code to see why the storage is treated like per request, but wasn't able to determine why the persisted data would reset. I'm under a tight deadline so moving on for now and come back to this later. I know at some point I might need to add Redux for persisting the datatables, but was hoping for a quick fix.

Ability to persist on submit, if needed

I've got a form which will be used in multiple pages, with different persistence needs.

You think It could be a thing to tweak formik-persist behaviour to for example persist on submit, based on a prop for example?

formik-persist.d.ts points to /Users/jared/workspace/github/jaredpalmer/ ..

Hi,

the formik-persist.d.ts published with the latest version (1.1.0) references ../../../../../../../Users/jared/workspace/github/jaredpalmer/formik-persist/node_modules/formik/dist/types resulting in a compile-time error for typescript users.

See https://unpkg.com/[email protected]/dist/formik-persist.d.ts

I saw that it's already fixed in 862aae8 and referenced in #18.

Am i missing something? Any chance you can publish a new version?

Republish please?

Hi @jaredpalmer thanks for writing this -- mind republishing to npm so the session storage changes become available? Thank you!

Also thought I would mention that your packager is adding your computer's path in the main .d.ts file

image

Thanks for the handy util -- I'm able to use it as is.

Usage with TypeScript

Hi, when using formik-persist with TypeScript I get this error:

formik-persist

The import is totally broken and pointing to a local file.

No persistency on setFieldValue()

When calling Formik.setFieldValue, the state of Formik changes, but since formik-persist saves on componentDidUpdate, the changes won't save.

Clear Values on Browser Close || Session Storage

I want to clear all the form values if the user closes the browser but there is no option to clear since it's using local storage. How Can I switch to session storage behavior? In sort, data should persist if the user reloads and data should clear if the user closes the browser.

initialValues reset storage

After a previous page change, the user find the form filled, but at this time, the localStorage is filled with initialValues, and if the user change page without touch the form, the initials values take place.

A possible solution : save basic formik state after mounting and test it in update

Action required: Greenkeeper could not be activated šŸšØ

šŸšØ You need to enable Continuous Integration on all branches of this repository. šŸšØ

To enable Greenkeeper, you need to make sure that a commit status is reported on all branches. This is required by Greenkeeper because it uses your CI build statuses to figure out when to notify you about breaking changes.

Since we didnā€™t receive a CI status on the greenkeeper/initial branch, itā€™s possible that you donā€™t have CI set up yet. We recommend using Travis CI, but Greenkeeper will work with every other CI service as well.

If you have already set up a CI for this repository, you might need to check how itā€™s configured. Make sure it is set to run on all new branches. If you donā€™t want it to run on absolutely every branch, you can whitelist branches starting with greenkeeper/.

Once you have installed and configured CI on this repository correctly, youā€™ll need to re-trigger Greenkeeperā€™s initial pull request. To do this, please delete the greenkeeper/initial branch in this repository, and then remove and re-add this repository to the Greenkeeper integrationā€™s white list on Github. You'll find this list on your repo or organizationā€™s settings page, under Installed GitHub Apps.

resetForm must be called twice in order to clear values from localstorage

Because the componentDidUpdate method uses prevProps instead of this.props, when resetForm is called, it saves the values that existed in the form before resetting. Because of this, I can reset a form, then when I navigate away from it and then back, all the values that were in the form prior to resetting it reappear.

componentDidUpdate(prevProps: PersistProps & { formik: FormikProps<any> }) {
if (!isEqual(prevProps.formik, this.context.formik)) {
this.saveForm(prevProps.formik);
}
}

My current workaround is to simply call resetForm() twice. The second time, redux-persist will correctly save the empty form

Formik-Persist doesn't persist my data on refresh

0

Hi I am currently using Formik and Formik-Persist to make a form wizard with 10 questions. On refresh (sometimes on first refresh, sometimes on second refresh) it happens to reset the values. Why?

Below you have the code. I didn't put the array of routes, but that's all.

      initialValues={{
        idealWeight: "",
        age: 0,
        kg: 0,
        cm: 0,
        kgFromBMI: 0,
        RMB: 0,
        bodyRecomposition: 0,
        gender: "",
        currentLifestyleEvaluationIMet: "",
        mainReason: [],
        currentHealthRisk: [],
        diabetesHistory: "",
        environment: "",
        email: "",
        password: "",

        activityLevel: 1.2
      }}
      onSubmit={() => {
        console.log("something");
      }}
    >
          <div className={styles.slide}>
            <Form>
              <ProgressBar
                progress={((findIndexOfCurrentRoute + 1) / pages.length) * 100}
              />
              <Switch>
                <Redirect from="/signup" exact to="/signup/idealWeight" />
                <div
                  className={styles.slide__center}
                  style={{ paddingTop: "3em" }}
                >
                  {pages.map((page: any, index: number) => (
                    <div style={{ width: "100%" }}>
                      <Route key={index} path={`/signup/${page.forRoute}`}>
                        {page.page}
                      </Route>
                    </div>
                  ))}
                </div>
              </Switch>
              <Persist name="signup-form" debounce={1} />
            </Form>
          </div>
        );
      }}
    </Formik>```

This is amazing!!!!

Just wanted to say - great work!! I was handling this manually before and it was a huge pain. Formik-persist was about as easy to integrate as I could imagine - almost too easy. Thank you!

Feature: save only on submit

I modified formik-persist on a local project to take a saveOnlyOnSubmit prop.
If anyone else thinks this is a useful feature, I can create a PR.

Just looking for feedback.

`isSessionStorage` prop doesn't work

Hey there, isSessionStorage prop doesn't work (stuff is still being set in localStorage) -- have provided in my app like so:

 <Persist
    name={withdrawalFormName(investmentId)}
    isSessionStorage // ...here
  />

I noticed the PR for this prop had been merged, but the latest version was before that change..?

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.