This TypeScript error occurs when trying to assign a value of type 'null' to a parameter that expects a type of 'Error | PromiseLike<Error | undefined> | undefined'

Currently, I am making use of the Mobx Persist Store plugin which allows me to store MobX Store data locally.

Although the documentation does not provide a TypeScript version, I made modifications to 2 lines of code (one in the readStore function and another in the writeStore function, which can be compared at https://github.com/quarrant/mobx-persist-store#with-mobx-6) to address TypeScript errors. However, this led to a new error:

import {
    persistence,
    useClear,
    useDisposers,
    isSynchronized,
    StorageAdapter,
} from 'mobx-persist-store'

import { FrameItStore } from '@/store/index'

function readStore(name: string) {
    return new Promise<string>((resolve) => {
        const data = localStorage.getItem(name) || '{}'
        resolve(JSON.parse(data))
    })
}

function writeStore(name: string, content: string) {
    return new Promise<Error | undefined>((resolve) => {
        localStorage.setItem(name, JSON.stringify(content))
        resolve(null)
    })
}

export default persistence({
    name: 'FrameItStore',
    properties: ['counter'],
    adapter: new StorageAdapter({
        read: readStore,
        write: writeStore,
    }),
    reactionOptions: {
        // optional
        delay: 2000,
    },
})(new FrameItStore())

An error is occurring with the null value in resolve(null) within the writeStore function.

The error message is as follows:

Argument of type 'null' is not assignable to parameter of type 'Error | PromiseLike<Error | undefined> | undefined'.ts(2345)

Any suggestions on how to resolve this issue?

Answer №1

unknown is not compatible with string or undefined. It appears that the return value of JSON.parse is unknown. To handle this, you need to check the type of the parsed data before resolving it. Conditional checks can help you determine if it's a string, in which case you can resolve it, or if it's undefined.

function readStore(name: string) {
    return new Promise((resolve) => {
        const data = localStorage.getItem(name) || '{}'
        const output = JSON.parse(data);
        if (typeof output === "string") resolve(output);
        resolve(undefined);
    })
}

Answer №2

After troubleshooting, I believe I have successfully resolved the issue. I made some changes by removing the JSON.parse from the readStore function and replacing resolve(null) with resolve(undefined) in the writeStore function. Here is the updated code snippet:

import {
    persistence,
    useClear,
    useDisposers,
    isSynchronized,
    StorageAdapter,
} from 'mobx-persist-store'

import { FrameItStore } from '@/store/index'

function readStore(name: string) {
    return new Promise<string>((resolve) => {
        const data = localStorage.getItem(name) || '{}'
        resolve(data)
    })
}

function writeStore(name: string, content: string) {
    return new Promise<Error | undefined>((resolve) => {
        localStorage.setItem(name, JSON.stringify(content))
        resolve(undefined)
    })
}

export const PersistState = persistence({
    name: 'FrameItStore',
    properties: ['counter'],
    adapter: new StorageAdapter({
        read: readStore,
        write: writeStore,
    }),
    reactionOptions: {
        // optional
        delay: 2000,
    },
})(new FrameItStore())

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to determine if a child component's property has changed within a method?

The child component is app-google-maps-panel and has 2 properties in the parent component: <div class="col-6"> <app-google-maps-panel [longitude]="longitude" [latitude]="latitude"></app-google-maps-panel> & ...

Error: selenium web driver java cannot locate tinyMCE

driver.switchTo().frame("tinymce_iframe"); String script="var editor=tinyMCE.get('tinymce_textarea');"; JavascriptExecutor js=(JavascriptExecutor) driver; js.executeScript(script); I'm encountering a WebDriverException while try ...

How should I start working on coding these sliders?

Which programming language should I use? My understanding of Java Script is limited, so coding them on my own might be challenging. What would be the essential code to begin with? Here are the sliders - currently just Photoshop images... ...

Angular - a simple method to determine the number of non-empty inputs in a complex template-driven form

As I work on multiple substantial Angular 11 template forms containing basic inputs like text, radiolists, and checkboxes, I am looking for the most effective method to calculate the percentage of completed inputs while the user is actively engaging with ...

Changing the color of a Navlink when focused

Can anyone help me modify the background color of a dropdown nav-link in Bootstrap? I am currently using the latest version and want to change it from blue to red when focused or clicked. I have included my navbar code below along with additional CSS, but ...

The AJAX callback is malfunctioning

Attempted to create a basic callback function to become familiar with it, but encountering an issue where it doesn't work upon page load. $(document).ready(getVideoId(function (response) { alert(response); })); function getVideoId(callba ...

Vue is refusing to display information for a certain API call

Within my next component, I have the following structure: <template> <div class="home"> <div class="container" v-if="data" > <Card v-for="result in data" :img="result.links[0]&q ...

How can multiple functions be grouped and exported in a separate file in Node.js?

Is there a way to consolidate and export multiple functions in nodejs? I want to gather all my utility functions in utils.js: async function example1 () { return 'example 1' } async function example2 () { return 'example 2' } ...

Is there a way for me to indicate to my custom component the specific location within an input message where a value should be displayed

I'm currently developing a value selector component in ionic/angular and I've encountered an issue with the message/title that I want to pass to the component. I want to be able to specify where the selected value should appear within the message ...

What is the method for including a data attribute in the text of a cell using Datatables Editor?

When initializing datatables along with editor, I typically use the following code: columns: [ { data: "name", className: 'noEdit clickTextToOpenModal' }, In this line of code, I am able to set the className attribute. However, is i ...

Is the textarea's shape out of the ordinary?

Most textareas are typically rectangular or square in shape, similar to this: However, I am interested in having a custom-shaped textarea, like the example below: Is it feasible to achieve? ...

Issue with CasperJS: The function this.waitForUrl is not defined and is causing an error

My casperJS script handles form filling, however I encountered the following error message: A TypeError occurred: 'undefined' is not a function (evaluating 'this.waitForUrl') I suspect this might be an issue with using an outdated ver ...

Sending a POST request and receiving a corresponding response in sequential order using NodeJS and a Python client

My Node.js server is constantly receiving POST requests from Python clients to invoke a backend service. Promises are utilized in the Node server's REST router to call the backend service and then send the results back to the client. Here's how ...

Replicate the process of transferring table rows to the clipboard, but exclusively copying the contents

Currently, I am attempting to copy a paginated table to my clipboard by referring to this guide: Select a complete table with Javascript (to be copied to clipboard). However, the issue lies in the fact that it only copies the data from the first page. In ...

Developing a GraphQL application with NestJS integrating the Passport LinkedIn strategy

Currently, my nestjs application is up and running on typescript, Graphql, Postgres with Jwt strategy all set. Now, I am looking to integrate the LinkedIn strategy into it. However, I'm unsure about where to begin as most available packages like do no ...

MUI Autocomplete is failing to update the value when onChange event is triggered

I have successfully fetched autocomplete options from an API and it displays the pre-selected options from the API. However, I am encountering an issue where I am unable to delete or add a value (category) once selected. For an online demo, you can check ...

Customize your popover content with Bootstrap settings

I've been on a quest to dynamically update the content of a Bootstrap popover using JavaScript, but unfortunately, the methods I've tried so far haven't worked out as expected : <!--object with the popover--> <input id="popoverlist ...

AngularJS - Issue with ng-mouseover not triggering controller function

I am struggling to get a function to trigger when my button is hovered over. Despite writing what I believe is the correct code, the function from my controller is not being called. Can anyone spot the issue? Below is the JavaScript code: angular.module( ...

Setting a JavaScript value for a property in an MVC model

I am currently working on an asp.net mvc application and I am in the process of implementing image uploading functionality. Below is the code for the image upload function: $(document).ready(function () { TableDatatablesEditable.init(); ...

Tips for retrieving the option text value following an onchange event in AngularJS

Whenever I change the selection in my dropdown menu for 'Cities', the alert is displaying the value of the previous selection instead of the current one. For example, if I select a state and then switch to Cities, the alert shows the text related ...