npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

use-neo4j

v0.3.13

Published

<div style="text-align:center"> <h1>React Hooks For Neo4j</h1>

Downloads

1,218

Readme

A set of components and hooks for building React applications that communicate to Neo4j. This is a package intended to speed up the development by reducing the amount of boilerplate code required. It is not intended for public-facing/production applications used by external users.

A basic example of this library has been configured in the Graph App Starter Kit for React template repository.

Installation

npm i --save use-neo4j

Usage

Creating a Driver instance

If you want to hard code the Driver credentials into your app, you can use the createDriver helper function to create a new Driver instance and pass it to the Neo4jProvider. This will cause the child components to be rendered immediately.

import { Neo4jProvider, createDriver } from 'use-neo4j'

const driver = createDriver('neo4j', 'localhost', 7687, 'neo4j', 'letmein')

ReactDOM.render(
  <React.StrictMode>
    <Neo4jProvider driver={driver}>
      <App />
    </Neo4jProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

Login Form

If you do not pass a driver instance to the Neo4jProvider, a login form will be displayed. You can pass default values through to the form using props:

import { Neo4jProvider } from 'use-neo4j'

ReactDOM.render(
  <React.StrictMode>
    <Neo4jProvider scheme="neo4j+s" host="myauradb.neo4j.io" port="7687" username="username" password="defaultpassword" database="mydb">
      <App />
    </Neo4jProvider>
  </React.StrictMode>,
  document.getElementById('root')
);

Hide Database

You can hide the database field from the form by passing showDatabase prop with a value of false

<Neo4jProvider showDatabase={false}>

Hide Host

You can force the user to connect to a specific database by providing the connection details to the Neo4jProvider and set the showHost prop to false.

<Neo4jProvider scheme="neo4j" host="localhost" port="7687" showHost={false}>

Hooks

Cypher

The cypher hooks will run a query against the Neo4j database using the driver instance passed to the Neo4jProvider or created during the login process. Each hook returns a Neo4jResultState which gives you access to a loading boolean, the result itself, any errors thrown during the query and helpers for accessing the first row.

export interface Neo4jResultState {
    cypher: string;
    params?: Record<string, any>;
    database?: string;
    loading: boolean;
    error?: Error;
    result?: QueryResult;
    records?: Neo4jRecord[];
    first?: Neo4jRecord;
    run: (params?: Record<string, any>, anotherDatabase?: string) => Promise<void | QueryResult>;
}

useReadCypher

useReadCypher(cypher: string, params?: Record<string, any>, database?: string): Neo4jResultState

Example code:

function MyComponent() {
    const query = `MATCH (m:Movie {title: $title}) RETURN m`
    const params = { title: 'The Matrix' }

    const { loading, first } = useReadCypher(query, params)

    if ( loading ) return (<div>Loading...</div>)

    // Get `m` from the first row
    const movie = first.get('m')

    return (
        <div>{movie.properties.title} was released in {movie.properties.year}</div>
    )
}

useWriteCypher

useWriteCypher(cypher: string, params?: Record<string, any>, database?: string): Neo4jResultState

Re-running a Query

The run function allows you to re-run a query if a prop changes. This should be wrapped in a useEffect function.

const [ query ] = useState('Matrix')
const { loading, records, run, } = useReadCypher('MATCH (m:Movie) WHERE m.title CONTAINS $query RETURN m LIMIT 12', { query })

// Listen for changes to `query` and re-run cypher if anything changes
useEffect(() => {
    run({ query })
}, [ query ])

Lazy Queries

If you don't want the query to run straight away (for example an update query), you can use the useLazyReadCypher or useLazyWriteCypher functions. The hooks return an array containing the function to run the query and the Neo4jResultState as the second parameter:

const [ updateMovie, { loading, first } ] = useLazyWriteCypher(
  `MATCH (m:Movie) WHERE id(m) = $id SET m += $updates, m.updatedAt = datetime() RETURN m.updatedAt as updatedAt`
)

const handleSubmit = e => {
    e.preventDefault()

    updateMovie({ id: int(0), updates: { title, plot } })
        .then(res => {
            res && setConfirmation(`Node updated at ${res.records[0].get('updatedAt').toString()}`)
        })
        .catch(e => setError(e))
}

return (
  <Button primary onClick={handleSubmit}>Update Node</Button>
)

The run function takes two optional arguments: an object of params and a database if different from the default.

Transactions

Transaction hooks give you a convenient way to open a new transaction.

export interface TransactionState {
    transaction: Transaction;
    run: Function,
    rollback: Function,
}

useReadTransaction

useReadTransaction(database?: string): TransactionState

useWriteTransaction

useWriteTransaction(database?: string): TransactionState

Example:

import { useReadTransaction } from 'use-neo4j'

const { transaction, commit, rollback } = useTransaction('mydb')

fetchSomeData()
    .then(properties => {
        // Use `run` to execute a query within the transaction
        return run(`CREATE (n:Node) SET n+= $properties`, { properties })
            //  If all is fine, commit the transaction
            .then(() => commit())
    })
    // If anything goes wrong, you can rollback the transaction
    .catch(e => rollback())

Schema Hooks

useSchema

Note: Requires APOC

The useSchema hook calls the apoc.meta.schema procedure and returns arrays of labels and relationship types.

Usage:

const { loading, labels, types } = useSchema(database)

Output:

export interface UseSchemaOutput {
    loading: boolean;
    labels: LabelSchema[];
    types: RelationshipTypeSchema[];
}

useDatabases

The useDatabases hook returns a list of databases for the current connection (version 4.0 and above). The hook runs the SHOW DATABASES query against the system database and returns a list of databases.

const { loading, error, databases } = useDatabases()

Output:

interface UseDatabasesOutput {
    loading: boolean;
    error?: Error;
    databases: Database[] | undefined
}

A Database object consists of:

interface Database {
    name: string;
    address: string;
    role: DatabaseRole;
    requestedStatus: DatabaseStatus;
    currentStatus: DatabaseStatus;
    error: string;
    default: boolean;
}

Connection Hooks

useConnection

The useConnection hook allows you to update the connection details for the driver held in Neo4jContext

useConnection(scheme: Neo4jScheme, host: string, port: string | number, username: string, password: string)

This hook will update the driver instance within the context and attempt to verify connectivity.