Skip to content

Avoid storing state that can be derived from other state. #2

@colorful-tones

Description

@colorful-tones

More feedback from @luisherranz

Avoid storing state that can be derived from other state.

const { state } = store( "...", {
  state: {
    get hasSucess() {
      const { status } = getContext();
      return status === "success";
    },
    get hasError() {
      const { status } = getContext();
      return status === "error";
    },
    get formMessage() {
      const { status } = getContext();
      if ( status === "success" ) return "Success!";
      if ( status === "error" ) return "Error!";
    }
  },
  actions: {
    *submitForm( event ) {
       // ...

       try {
        yield fetch( context.ajaxUrl, {
          method: 'POST',
          credentials: 'same-origin',
                body: formData
        }).then( r => r.text() )
        context.status = "success";
      } catch( error ) {
        console.error( 'Error:', error );
        context.status = "error";
      }
    },
  }
});

This keeps things more declarative and avoids out-of-sync issues when the code starts getting complex.

I hope that helps 🙂

Metadata

Metadata

Labels

enhancementNew feature or request

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions