Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

RxJS pipes undefined

I’m running a json-server database with some random data:

{
  "status": [
        {
            "id": 3,
            "uid": 1,
            "isActive": false
        },
        {
            "id": 4,
            "uid": 3,
            "isActive": true
        }
    ]
}

and I’m using this function to fetch some data:

export async function getStatus(uid: number): Promise<Status>{
    return fetch(`http://localhost:3000/status?uid=${uid}`).then(res => res.json())    
}

And then, when I run this code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function isActive(id: number): Observable<boolean>{
    
    return from(getStatus(id))
        .pipe(map(value => {
                console.log (`Value of in map pipe: ${JSON.stringify(value)}`)
                return value.isActive
            })) 
}

function main() {
    isActive(1).subscribe({
            next: (value => console.log('answer: ' + value))
        })                 
}

main()

it returns this output:

Value of in map pipe: [{"id":3,"uid":1,"isActive":false}]
answer: undefined // <-----

The expected output:

Value of in map pipe: [{"id":3,"uid":1,"isActive":false}]
answer: false // <-----

Why do I get undefined instead of false?

>Solution :

In your console log I can see a array.
This code will work:

function isActive(id: number): Observable<boolean>{
    
    return from(getStatus(id))
        .pipe(map(value => {
                console.log (`Value of in map pipe: ${JSON.stringify(value)}`)
                return Array.isArray(value) ? value[0].isActive : false; // you can replace false with value.isActive
            })) 
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading